0

I have an associative array that looks like this:

Array (
    [0] => Array (
        [amount] => 3
        [name] => Chuck
    )
    [1] => Array (
        [amount] => 2
        [name] => Steve
    )
    [2] => Array (
        [amount] => 5
        [name] =>
    )
    [3] => Array (
        [amount] => 4
        [name] => Chuck
    )
    [4] => Array (
        [amount] =>
        [name] => Chuck
    )
)

I need to remove values that are missing a name or amount e.g. [2] and [4] and then sum the totals for each name so that the final array is:

Array (
    [0] => Array (
        [amount] => 7
        [name] => Chuck
    )
    [1] => Array (
        [amount] => 2
        [name] => Steve
    )
) 
Dave
  • 44,275
  • 12
  • 65
  • 105
zeros-and-ones
  • 4,227
  • 6
  • 35
  • 54

2 Answers2

2

For anyone looking for this nowadays, this would be much cleaner:

$sum = array_sum(array_column($data, 'amount'));
galdikas
  • 1,609
  • 5
  • 19
  • 43
0

Try this:

$starting_array = array( ... ); // Initial array with your setup
$final_array = array();
$sum = 0;

foreach ($starting_array as $idx => $data) {
  if (!empty($data['amount']) && !empty($data['name'])) {
    $final_array[$idx] = $data;
    $sum += $data['amount'];
  }
}

// After looping through all of the items, $final_array should contain all
// of the specific items that have an amount and name set. In addition, the
// total of all of the amounts will be in $sum.

Take a look at php's empty(). Note: If 0 is an allowed value, you may want to use is_null() instead.

Aiias
  • 4,683
  • 1
  • 18
  • 34
  • Thanks Aiias, that worked for cleaning up the array. What does $idx = $data do? Is this similar to $key = > $value? Also, do you have any advice for summing the values for each name? Thanks again. – zeros-and-ones Mar 30 '13 at 02:50
  • @CameronMacfarlane - In a php `foreach` loop, you loop through all of the items in the array. When you use the syntax `foreach ( $ARRAY as $KEY => $VALUE )` you will get the key of each item and its corresponding value (at that key: e.g. `$ARRAY[$KEY] = $VALUE` for every `$KEY`). I would definitely recommend looking further into php's [`foreach`](http://php.net/manual/en/control-structures.foreach.php) for a more complete explanation. In terms of summing the values for each name, check my edit. – Aiias Mar 30 '13 at 03:00
  • Hi Aiias, thanks again. I understand how $key => $value works in a foreach loop. I was just asking is $idx=> $data is the same, I have never seen this syntax. Also, I wanted to sum values for each name, opposed to the total of all. I tried the edit, it didn't work for summing the names amount. – zeros-and-ones Mar 30 '13 at 03:16
  • I think I found my answer here http://stackoverflow.com/questions/14195916/associative-array-sum-values-of-the-same-key – zeros-and-ones Mar 30 '13 at 03:26
  • @CameronMacfarlane - Yup, that is definitely another way to do it. – Aiias Mar 30 '13 at 03:39