简体   繁体   中英

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

对于现在寻找这个的人来说,这会更干净:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM