PHP Sum Of arrays inside a multidimensional array

2019-09-06 20:59发布

问题:

Need a little help here with summing up arrays inside a multi dimensional php array

Eg Multidimensional array

Array
(
    [0] => Array
        (
            [0] => 30
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 2
            [7] => 5
        )

    [1] => Array
        (
            [0] => 50
            [1] => 4
            [2] => 8
            [3] => 4
            [4] => 4
            [5] => 6
            [6] => 9
            [7] => 2
        )
)

I want to have a result array that will be holding sum of both these arrays like this

Array
(
    [0] => 80
    [1] => 9
    [2] => 14
    [3] => 11
    [4] => 12
    [5] => 15
    [6] => 11
    [7] => 7
)

Any help will be greatly appreciated

Thanks!

回答1:

This should work for arrays like the one of your example ($arr is an array like the one in your example, I haven't defined it here for simplicity's sake):

$res = array();
foreach($arr as $value) {
    foreach($value as $key => $number) {
        (!isset($res[$key])) ?
            $res[$key] = $number :
            $res[$key] += $number;
    }
}

print_r($res);


回答2:

This should work for you:

<?php

    $arr = array(
            array(30, 5, 6, 7, 8, 9, 2, 5), 
            array(50, 4, 8, 4, 4, 6, 9, 2)
        );

    $result = array();

    foreach($arr[0] as $k => $v)
        $result[$k] = array_sum(array_column($arr, $k));

    print_r($result);

?>

Output:

Array ( [0] => 80 [1] => 9 [2] => 14 [3] => 11 [4] => 12 [5] => 15 [6] => 11 [7] => 7 )

EDIT:

If your php version is under 5.4 you can use this simple workaround:

function arrayColumn(array $array, $column_key, $index_key=null){
    if(function_exists('array_column ')){
        return array_column($array, $column_key, $index_key);
    }
    $result = [];
    foreach($array as $arr){
        if(!is_array($arr)) continue;

        if(is_null($column_key)){
            $value = $arr;
        }else{
            $value = $arr[$column_key];
        }

        if(!is_null($index_key)){
            $key = $arr[$index_key];
            $result[$key] = $value;
        }else{
            $result[] = $value;
        }

    }

    return $result;
}

(Note that you have to use arrayColumn())

From the manual comments: http://php.net/manual/de/function.array-column.php#116301