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.

Riza Khan
  • 2,712
  • 4
  • 18
  • 42
  • What would you like to return eventually? You're not making that clear in your question – Anwar El Bo Oct 30 '21 at 02: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 – Riza Khan Oct 30 '21 at 03:06
  • Splat-packing is inefficient and verbose. https://stackoverflow.com/q/57725811/2943403 Your samle input and desired result is Unclear. – mickmackusa Oct 30 '21 at 05:51

1 Answers1

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",
       ],
     ],
   }

Lupinity Labs
  • 2,099
  • 1
  • 15
  • 23