I have a multidimensional associative array that I need to loop through and collect the product specific data. Please see below:
$rawData = array(
array(
'sku' => 'product1',
'quantity' => '3'
),
array(
'sku' => 'product2',
'quantity' => '3'
),
array(
'sku' => 'product1',
'quantity' => '2'
)
);
$collectedData = array();
for ($i = 0; $i < count($rawData); $i++) {
$collectedData += array($rawData[$i]['sku'] => $rawData[$i]['quantity']);
}
print_r($collectedData);
This outputs the following:
Array
(
[product1] => 3
[product2] => 3
)
What I need however is that if the array key sku
already exists in the $collectedData
array, for the quantity of the array value to be added to the already existing quantity.
So this would be my desired result (as product1
exists twice with values 2
and 3
):
Array
(
[product1] => 5
[product2] => 3
)
Is there an easy way of doing this? Thank you very much for any help in advance.