flyingL123 flyingL123 - 1 month ago 5
PHP Question

Is there an array function in PHP to do this instead of a foreach loop?

In PHP, is there an array function do the same thing as the code below? I'm wondering if it's possible with something like

array_map
or
array_reduce
in such a way that the
$items
array does not need to be declared beforehand.

$data = [
['order_product_id' => 123, 'quantity' => 1],
['order_product_id' => 456, 'quantity' => 2],
['order_product_id' => 567, 'quantity' => 3],
];

$items = [];

foreach ($data as $item) {
$items[$item->order_product_id] = ['quantity' => $item->quantity];
}

print_r($items);

/*
Array
(
[123] => ['quantity' => 1]
[456] => ['quantity' => 2]
[789] => ['quantity' => 3]
)
*/

Answer

Array_reduce will do what you want as it hides the declaration of the output array in the 'initial value' of the carry parameter. Also, rather than 'reduce' it actually adds entries to the output.

It isn't as easy to understand as your original version. And is no faster.

$data = [
  (object) ['order_product_id' => 123, 'quantity' => 1],
  (object) ['order_product_id' => 456, 'quantity' => 2],
  (object) ['order_product_id' => 567, 'quantity' => 3],
];


$items = array_reduce($data, 
            function ($out, $item) {
                $out[$item->order_product_id] = ['quantity' => $item->quantity];
                return $out;                                    
            },
            array());

print_r($items);

Output:

Array(
    [123] => Array([quantity] => 1)

    [456] => Array([quantity] => 2)

    [567] => Array([quantity] => 3)
)
Comments