Home > Software design >  PHP: array_map to return specific array of objects
PHP: array_map to return specific array of objects

Time:10-31

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.

CodePudding user response:

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

  • Related