How to sum all column values in multi-dimensional array?

后端 未结 20 2522
花落未央
花落未央 2020-11-22 00:57

How can I add all the columnar values by associative key? Note that key sets are dynamic.

Input array:

Arr         


        
20条回答
  •  无人及你
    2020-11-22 01:33

    Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

    function array_add_by_key( $array1, $array2 ) {
        foreach ( $array2 as $k => $a ) {
            if ( array_key_exists( $k, $array1 ) ) {
                $array1[$k] += $a;
            } else {
                $array1[$k] = $a;
            }
        }
        return $array1;
    }
    

提交回复
热议问题