如何使用array_sum PHP

时间:2018-08-07 14:28:30

标签: php arrays

我有这样的数据数组:

$marks = array( 
        "mohammad" => array (
           "physics" => 35,
           "maths" => 30,   
           "chemistry" => array(
              "c1" => 80
           ),
        ),

        "qadir" => array (
           "physics" => 30,
           "maths" => 32,
           "chemistry" => array(
              "c1" => 70
           ),
        ),

        "zara" => array (
           "physics" => 31,
           "maths" => 22,
           "chemistry" => array(
              "c1" => 60
           ),
        )
     );

如何汇总所有数据c1? 80 + 70 + 60 = 210

我尝试过

array_sum(array_column($marks [0], "c1"))

但是有错误,请给我答复

2 个答案:

答案 0 :(得分:1)

$finalMark=0;

foreach($marks as $row){
    $finalMark+=$row['chemistry']['c1'];
}


echo $finalMark;

此代码实际上将遍历您的嵌套数组,找到所有c1字段并将它们加到$finalMark字符串中

输出为:210

答案 1 :(得分:1)

正如我告诉您的那样,您错了,因为c1在密钥chemistry中,因此它不能与array_column一起使用。

你可以做到

$sum = 0;
//This is better than array_column in your case !
foreach($marks as $mark) {
   $sum += $mark['chemistry']['c1'];
}

希望这会有所帮助