开发者

Sum all values in a 2d array

How can I sum all of the values in an array of arrays?

Sample array:

[
    [0],
    [0],
    [1, 6, 0]
]

Desired output:开发者_开发百科 7


echo array_sum(
    call_user_func_array('array_merge', $array)
);
//or
echo array_sum(
    array_map('array_sum', $array)
);


Use recursion. This will sum an array to any depth (ignoring php imposed call stack depth limit):

function sum_all($arr)
{
    $sum = 0;

    foreach ($arr as $val)
    {
        if (is_array($val))
            $sum += sum_all($val);
        else
            $sum += $val;
    }

    return $sum;
}


I guess those three arrays are actually all part of a top-level array, like this:

$array = array( array( 0 ), array( 1, 2, 3, 4 ), array( 5, 6 ) );

$sum = 0;
for ( $i = 0; $i < count( $array ); $i++ )
{
    $sum += array_sum( $array[$i] );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜