PHP Question

combine the same values in array

Help me pls combine array values.
I have the same array:
In my case i should save customers name like a key.

Array
(
[Test Name] => Array
(
[0] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
10
)
[1] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
20
)
[3] => Array
(
[name] =>
apple
[id] =>
23402
[qua] =>
1
)

[5] => Array
(
[name] =>
cherry
[id] =>
40017
[qua] =>
7
)


How to get something like this:

Array
(
[Test Name] => Array
(
[0] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
30 // summ quantity but unique name and id
)
[1] => Array
(
[name] =>
apple
[id] =>
23402
[qua] =>
1
)

[2] => Array
(
[name] =>
cherry
[id] =>
40017
[qua] =>
7
)


In my case i should save customers name like a key.
Then i will upload this on a table.

Answer

You can use array_map and array_reduce to accomplish it:

$results = array_map(function ($result) {
    return array_reduce($result, function ($carry, $item) {
        if (isset($carry[$item['id']])) {
            $carry[$item['id']]['quantity'] += $item['quantity'];
        } else {
            $carry[$item['id']] = $item;
        }
        return $carry;
    }, array());
}, $results);

From the documentation:

array_map() returns an array containing all the elements of array1 after applying the callback function to each one.

array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.

In our case the callback given to the array_reduce function returns a final array which contains unique items by id.