This is a section of my array:
[1] => Array
(
[quantity] => 2
[product_id] => 1
[option_id] => 22
)
[2] => Array
(
[quantity] => 2
[product_id] => 2
[option_id] => 22
)
[3] => Array
(
[quantity] => 3
[product_id] => 2
[option_id] => 22
)
[4] => Array
(
[quantity] => 1
[product_id] => 2
[option_id] => 25
)
I wish to group/merge the subarrays by product_id
and option_id
.
Upon merging subarrays, I would like to sum the quantity
values.
In my sample data, both subarrays [2]
and [3]
have 'product_id'=>2
and 'option_id'=>22
. They should be merged together into one subarray with a quantity
value of 5
.
This is my expected output:
[1] => Array
(
[quantity] => 2
[product_id] => 1
[option_id] => 22
)
[2] => Array
(
[quantity] => 5
[product_id] => 2
[option_id] => 22
)
[3] => Array
(
[quantity] => 1
[product_id] => 2
[option_id] => 25
)
*My first level keys are not associated with their subarrays so they may be changed in the process. I do want the first level keys to be incremented from 1
not 0
.
You only need to build compound temporary keys and then overwrite the keys.
By writing an initial element (
null
in this case) then deleting the element after the loop is finished, you ensure that the first key in the result array is1
.To avoid the "messiness" of the repeated long-winded compound key, you can save the the dynamic key as a variable in the first line inside of the foreach loop, then reference that variable in the three respective locations in the condition block.
Code (Demo)
Output:
One possible solution to your problem consists of the following steps:
for
loop to examine every element in the array with every element after it.array_values
to make the array compact again.Code:
Note: Your question shows no effort made in your part. I'm assuming you are completely lost and have no idea what to do and that's the only reason I'm answering. If you have made any effort that did not work as expected include it in your question, as that will prompt other users to answer too and perhaps give you better answers than mine.