Accumulate 2D array by index

I have an array that looks like this:

Array ( [0] => Array ( [amount] => 60.00 [store_id] => 1 ) [1] => Array ( [amount] => 40.00 [store_id] => 1 ) [2] => Array ( [amount] => 10.00 [store_id] => 2 ) ) 

Which would be a good way to reduce the array to a similar array, which sums up the "amount" associated with store_id.

For an instance, I would like to get the following:

 Array ( [0] => Array ( [amount] => 100.00 [store_id] => 1 ) [2] => Array ( [amount] => 10.00 [store_id] => 2 ) ) 
+4
source share
2 answers

To reproduce exactly what you asked for:

 <?php $stores = array(); $result = array(); foreach($rows as $i => $entry) { if (false === ($j = array_search($entry['store'], $stores))) { $stores[$i] = $entry['store']; $result[$i] = $entry; } else { $result[$j]['amount'] += $entry['amount']; } } 
+2
source

To clarify Traun’s answer, you want your array to be indexed by store_id. In the end you want:

  array ( [1] => 100.00 [2] => 10.00 ) 

If you cannot just build it from the very beginning, but you are forced to work with this original array structure (let's call it $stores ), do the following:

  $totals = array(); foreach ($stores as $store) { if (!array_key_exists($store['store_id'], $totals)) { $totals[$store['store_id']] = $store['amount']; } else { $totals[$store['store_id']] += $store['amount']; } } 

There are many ways to check this array. empty and isset enough.

+2
source

Source: https://habr.com/ru/post/1305245/


All Articles