使用php在多维关联数组中组合和求和值

时间:2013-03-30 02:29:02

标签: php arrays multidimensional-array sorting associative

我有一个看起来像这样的关联数组:

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

我需要删除缺少名称或金额的值,例如[2]和[4]然后将每个名称的总和相加,以便最终的数组为:

Array (
    [0] => Array (
        [amount] => 7
        [name] => Chuck
    )
    [1] => Array (
        [amount] => 2
        [name] => Steve
    )
) 

2 个答案:

答案 0 :(得分:2)

对于如今正在寻找这个东西的人来说,这会更清洁:

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

答案 1 :(得分:0)

试试这个:

$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.

看一下php的empty()。注意:如果0是允许值,则可能需要使用is_null()