zeros-and-ones
zeros-and-ones

Reputation: 4438

Combine and sum values in multi-dimensional associative array using php

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

Upvotes: 0

Views: 1714

Answers (2)

galdikas
galdikas

Reputation: 1669

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

$sum = array_sum(array_column($data, 'amount'));

Upvotes: 2

Aiias
Aiias

Reputation: 4748

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.

Upvotes: 0

Related Questions