动态数组中特定索引值的总和

时间:2017-10-27 10:32:37

标签: php arrays

我有一个格式如下的数组

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 2000
            [4] => 2000
            [5] => 4000
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )

    [1] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 500
            [3] => 500
            [4] => 500
            [5] => 800
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )
 [2] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 500
            [3] => 500
            [4] => 500
            [5] => 800
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )

)

我尝试过使用for和while循环但没有获得所需的输出 我想要以下格式的总和。

var a1=array[0][0]+array[1][0]+array[2][0];
var a2 = array[0][1]+array[1][1]+array[2][1];

谢谢

3 个答案:

答案 0 :(得分:0)

就像你想要将索引编号3加起来

$items = array(
 array(1 => 1, 2 => 'White Shirt', 3 => 2),
 array(1 => 2, 2 => 'Blue Shirt', 3 => 3)
);
echo "<pre>";
print_r($items);

echo array_sum(array_column($items, 3));

输出是第3个索引中的5个

答案 1 :(得分:0)

使用call_user_function_arrayarray_maparray_sum函数的简短解决方案:

$arr = [    // shortened version
    [0, 500, 500, 800],
    [0, 500, 800, 2000],
    [0, 500, 500, 5400],
];

$result = array_map(function($a){
    return array_sum($a);
}, call_user_func_array('array_map', array_merge([null], $arr)));

print_r($result);

输出:

Array
(
    [0] => 0
    [1] => 1500
    [2] => 1800
    [3] => 8200
)

答案 2 :(得分:0)

这是一个利用array_sum()array_column()的解决方案。它假设每个子数组具有相同数量的值。

$arr = [ //<-- test data
    [4,1,6,8,3],
    [11,59,4,0,3],
    [2,4,8,8,131]
];

//for each 'column', sum the total across all sub-arrays
for($s=0; $s<count($arr[0]); $s++)
    ${'sum_'.$s} = array_sum(array_column($arr, $s));

echo $sum_4; //e.g. 137