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

后端 未结 20 2841
花落未央
花落未央 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:17

    We need to check first if array key does exist.

    CODE:

    $sum = array();
    foreach ($array as $key => $sub_array) {
        foreach ($sub_array as $sub_key => $value) {
    
            //If array key doesn't exists then create and initize first before we add a value.
            //Without this we will have an Undefined index error.
            if( ! array_key_exists($sub_key, $sum)) $sum[$sub_key] = 0;
    
            //Add Value
            $sum[$sub_key]+=$value;
        }
    }
    print_r($sum);
    

    OUTPUT With Array Key Validation:

    Array
    (
        [gozhi] => 10
        [uzorong] => 1
        [ngangla] => 8
        [langthel] => 10
    )
    

    OUTPUT Without Array Key Validation:

    Notice: Undefined index: gozhi in F:\web\index.php on line 37
    
    Notice: Undefined index: uzorong in F:\web\index.php on line 37
    
    Notice: Undefined index: ngangla in F:\web\index.php on line 37
    
    Notice: Undefined index: langthel in F:\web\index.php on line 37
    
    Array
    (
        [gozhi] => 10
        [uzorong] => 1
        [ngangla] => 8
        [langthel] => 10
    )
    

    This is a bad practice although it prints the output. Always check first if key does exist.

提交回复
热议问题