两个不同的两个多维数组的数组和

时间:2018-10-12 09:48:17

标签: php arrays

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [headName] => Cow Loan
                    [netAmount] => 15000
                    [netDeposite] => 1000
                    [deducted] => 480
                    [net_DUE] => 14520
                )            
        )

    [2] => Array
        (
            [0] => Array
                (
                    [headName] => Cow Loan
                    [netAmount] => 4566
                    [netDeposite] => 566
                    [deducted] => 0
                    [net_DUE] => 4566
                )
)

我如何求和多维数组?

我只想总结所有数组中deducted的出现情况

第一个数组扣除值是480,第二个扣除值是0,所以数组总和应该是

[0] => Array ( [deducted] => 480 ) 

4 个答案:

答案 0 :(得分:2)

尝试如下

 $totalDeducted = 0;

 foreach($yourArrayVariable as $key => $value){
     $totalDeducted += $value[0]['deducted'];
 }

答案 1 :(得分:1)

您可以使用array_reduce

$array = array(
    array(["headName"=>'Cow Loan',"netAmount"=>15000,"netDeposite"=>1000,"deducted"=>480,"net_DUE"=>14520]),
    array(["headName"=>'Cow Loan',"netAmount"=>4566,"netDeposite"=>566,"deducted"=>0,"net_DUE"=>4566]),
);

$totalDeducted = array_reduce($array, function($sum, $v) {
    $sum += $v[0]['deducted'];
    return $sum;
});

echo $totalDeducted;//480

答案 2 :(得分:0)

您可以按照以下步骤进行操作

    $array = array(
                array("headName"=>'Cow Loan',"netAmount"=>15000,"netDeposite"=>1000,"deducted"=>480,"net_DUE"=>14520),
                array("headName"=>'Cow Loan',"netAmount"=>4566,"netDeposite"=>566,"deducted"=>0,"net_DUE"=>4566),       
    );


    $deducted=0;
    foreach($array as $values){ 
        $deducted = $deducted+$values['deducted'];
    }

    echo $deducted;

答案 3 :(得分:0)

目前尚不清楚您的第二级可能包含多个子数组,但是我将设计一种解决方案来适应这种可能性。

代码:(Demo

synchronized

也就是说,如果第二级中只有单个子数组(仅存在$array = [ [["headName"=>'Cow Loan',"netAmount"=>15000,"netDeposite"=>1000,"deducted"=>480,"net_DUE"=>14520]], [["headName"=>'Cow Loan',"netAmount"=>4566,"netDeposite"=>566,"deducted"=>0,"net_DUE"=>4566]], ]; $total = 0; foreach ($array as $level1) { foreach ($level1 as $level2) { $total += $level2['deducted']; } } echo "Deducted: $total"; // Deducted: 480 ),则应该重组数据存储以简化处理。

考虑一下:

[0]