PHP Sum Of arrays inside a multidimensional array

前端 未结 2 656
感动是毒
感动是毒 2021-01-27 12:26

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

Eg Multidimensional array

Array
(
    [0] => Array
        (
              


        
相关标签:
2条回答
  • 2021-01-27 12:55

    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);
    
    0 讨论(0)
  • 2021-01-27 13:03

    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

    0 讨论(0)
提交回复
热议问题