使用php对多维关联数组中的值进行组合和求和



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

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

对于现在正在寻找这个的人来说,这将是更清晰的:

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

试试这个:

$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()来代替。

相关内容

  • 没有找到相关文章

最新更新