0

I have a codepen here which shows a large array of objects. From which I would like to extract a specific property and display as shown in the console log, but in PHP.

Unfortunately for me, I'm quite new to PHP and can't seem to figure it out:

My attempt so far:

       $suppliersNotInDB = array_map(function ($order) {                                                                                                                                                 
            if (isset($order->items) && is_array($order->items)) {
                return array_map(function ($item) {
                    return [...$item];
                }, $order->items);
          }
       }, $ordersData);

Which, I understand isn't even remotely close, but I've been at it for hours now. Any help would be appreciated.

The long and short is that I want to perform this filtering and sorting in the backend(Laravel), not the frontend, where there is already too much going on.

3
  • What would you like to return eventually? You're not making that clear in your question Commented Oct 30, 2021 at 2:51
  • If you open the codepen and look at the console log, you will see an array of objects. That is what I need the results to be Commented Oct 30, 2021 at 3:06
  • Splat-packing is inefficient and verbose. stackoverflow.com/q/57725811/2943403 Your samle input and desired result is Unclear. Commented Oct 30, 2021 at 5:51

1 Answer 1

1

Since you are using Laravel, start using Collections.

If I understood correctly what you are trying to do in your Javascript example, this can be done in a one-liner:

$suppliersNotInDB = collect($ordersData)
    ->pluck('items')
    ->flatten()
    ->pluck('supplier')
    ->unique()
    ->map(
        fn($supplier) => ['name' => $supplier, 'lowercased' => strtolower($supplier)]
    )
    ->values();

This can probably be further refined, just quickly jotted it down to reproduce your result.

The output of this would then be:

=> Illuminate\Support\Collection {#4999
     all: [
       [
         "name" => "Walmart",
         "lowercased" => "walmart",
       ],
       [
         "name" => "Bestbuy",
         "lowercased" => "bestbuy",
       ],
       [
         "name" => "TCI",
         "lowercased" => "tci",
       ],
       [
         "name" => "lkj",
         "lowercased" => "lkj",
       ],
       [
         "name" => "Thousand Needles",
         "lowercased" => "thousand needles",
       ],
     ],
   }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.