tags:

views:

33

answers:

2

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
        )
)

What would be a good method to reduce the array to a similar array that totals the 'amount' related to a store_id.

For Instance I'd like to get this:

Array
(
    [0] => Array
        (
            [amount] => 100.00
            [store_id] => 1
        )


    [2] => Array
        (
            [amount] => 10.00
            [store_id] => 2
        )
)
+2  A: 

To reproduce exactly what you've 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'];
  }
}
jakemcgraw
+1 for EXACTLY what he wanted. I went for the 'use a better solution' approach.
Tesserex
thank you very much
Tegan Snyder
+2  A: 

To elaborate on Thrawn's answer, what you want is for your array to be indexed by store_id. What you want in the end is:

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

If you can't just construct that from the start, but you are forced to work with this original array structure (let's call it $stores), do this:

    $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's a bunch of ways to do that array_key_exists check. empty and isset would both suffice.

Tesserex
thanks for your input array_key_exists has cause me some issues in magento before.
Tegan Snyder