Sum of subarray values

依然范特西╮ 提交于 2019-12-25 03:26:47

问题


Array
(
    [1~course2 20:00] => Array
        (
            [0] => Array
                (
                    [pid] => 30
                    [anz_tn] => 6
                )

            [1] => Array
                (
                    [pid] => 30
                    [anz_tn] => 4
                )

            [2] => Array
                (
                    [pid] => 30
                    [anz_tn] => 5
                )
        )

    [2~Course2 08:30] => Array
        (
            [0] => Array
                (
                    [pid] => 30
                    [anz_tn] => 5
                )

            [1] => Array
                (
                    [pid] => 11
                )

            [2] => Array
                (
                    [anz_tn] => 4
                )
)

....

How can I get the sum of all the "anz_tn" for each subarray? (sum of all [0]['anz_tn'],[1]['anz_tn'], etc..)

I've tried to use $all[][$i]['anz_tn'] but this fails. ($all is the main array, $i is the count of subarrays). Is there a way using array_sum?

Thanks!


回答1:


please try like this,

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {
    if ($id == 'anz_tn')
      $sumArray[$id]+=$value;
  }
}

print_r($sumArray);



回答2:


Thank you, Manadh!

This was pointing me in the right direction. One level of the array was missing (resulting in 'unsupported operand error'), so in the end I came up with this:

$sumArray = array();
foreach ($groupasweek as $s1k=>$s1v) {
    foreach ($s1v as $s2k=>$s2v) {
        foreach ($s2v as $id=>$value) {
            if ($id == 'anz_tn') {
                $sumArray[$s1k][$id] += $value;
            }           
        }
    }
}

Btw, where can I accept an answer?



来源:https://stackoverflow.com/questions/29362356/sum-of-subarray-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!