子阵列值的总和

时间:2015-03-31 06:52:08

标签: php dynamic-arrays

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

...

如何获得每个子阵列的所有“anz_tn”的总和? (所有[0] ['anz_tn'],[1] ['anz_tn']等的总和。)

我试图使用$ all [] [$ i] ['anz_tn'],但这失败了。 ($ all是主数组,$ i是子数组的数量)。有没有办法使用array_sum?

谢谢!

2 个答案:

答案 0 :(得分:0)

请尝试这样,

$sumArray = array();

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

print_r($sumArray);

答案 1 :(得分:0)

谢谢你,Manadh!

这指向了正确的方向。数组的一个级别丢失(导致“不支持的操作数错误”),所以最后我想出了这个:

$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;
            }           
        }
    }
}
顺便问一下,我在哪里可以接受答案?