试图获得数组值的总和

时间:2013-10-25 18:36:15

标签: php

我得到了这个数组,我正在努力计算[za]值的总和,但没有任何成功。

我的最后一次尝试是这段代码:

foreach ( $sumza as $sumzakey ) {
              $sum += $sumza[$sumzakey]['za'];
}





Array
(
    [0] => Array
        (
            [za] => 3600
        )

    [1] => Array
        (
            [za] => 7200
        )

    [2] => Array
        (
            [za] => -27360
        )

    [3] => Array
        (
            [za] => 3600
        )

    [4] => Array
        (
            [za] => 
        )

    [5] => Array
        (
            [za] => 3600
        )

    [6] => Array
        (
            [za] => 3600
        )

    [7] => Array
        (
            [za] => 3600
        )

    [8] => Array
        (
            [za] => 7200
        )

    [9] => Array
        (
            [za] => 7740
        )

    [10] => Array
        (
            [za] => 
        )

    [11] => Array
        (
            [za] => -27360
        )

    [12] => Array
        (
            [za] => 7200
        )

    [13] => Array
        (
            [za] => 3600
        )

    [14] => Array
        (
            [za] => 8640
        )

    [15] => Array
        (
            [za] => 3600
        )

    [16] => Array
        (
            [za] => 6840
        )

    [17] => Array
        (
            [za] => 
        )

    [18] => Array
        (
            [za] => 5040
        )

    [19] => Array
        (
            [za] => 5040
        )

    [20] => Array
        (
            [za] => 5040
        )

    [21] => Array
        (
            [za] => -27360
        )

    [22] => Array
        (
            [za] => 
        )

)

1 个答案:

答案 0 :(得分:2)

尝试:

$sum = 0;
foreach ( $sumza as $sumzakey ) {
    $sum += $sumzakey['za'];
}

$sumzakey实际上代表$sumza内的每个数组。如果你想使用你的方法,你会这样做:

$sum = 0;
foreach ( $sumza as $sumzakey => $sumzavalue ) {
    $sum += $sumza[$sumzakey]['za'];
}

在这种情况下,您现在拥有$sumza中每个数组元素的数组键,并可以使用它来访问$sumza中的每个数组元素。但这不是必要的,也不像上面的代码那么清晰。