Sum the values of two associative multi-dimensional arrays in PHP

后端 未结 3 462
失恋的感觉
失恋的感觉 2020-12-21 18:36

I am trying to sum the values of two associative arrays. This is the first array:

Array
(
[Jan 01, 2013] => Array
    (
        [COM] => 100
        [         


        
3条回答
  •  春和景丽
    2020-12-21 19:22

    Try this:

     1,
          'b' => 2
       );
    
        $array_02 = array(
          'a' => 0,
          'b' => 1,
          'c' => 2
        );
    
        /** first we should get the array keys union
         * this is too long...,so you can make it better :D
         * you can make this more readable
         */
        $keyUnion = array_unique(array_merge(array_keys($array_01), array_keys($array_02))); 
        $res = array();
    
        //sum
        foreach ($keyUnion as $k => $v) {
            $res[$v] = (isset($array_01[$v]) ? $array_01[$v] : 0) + (isset($array_02[$v]) ? $array_02[$v] : 0);
        }
    
        print_r($res);
    ?>
    

    Notice: code only get the one-dimensional associative sum

提交回复
热议问题