merge/sum multi dimentional array php

后端 未结 1 1277
北海茫月
北海茫月 2020-12-20 03:52

I\'m trying to merge/sums 2 arrays that can contain integers or more arrays (themselves containing integer).

When the values are integers, I need to sum them in the

相关标签:
1条回答
  • 2020-12-20 04:15

    You can get all the keys for the foreach loop, live demo.

    Note, you also can check if a key of any array is undefined, then save the defined value for the key.

    function sumArrayValues($array1, $array2)
    {
        $keys = array_keys($array1 + $array2);
        foreach ($keys as $key) 
        {
            if (is_array($array1[$key]) || is_array($array2[$key]))
                $array1[$key] = sumArrayValues($array1[$key], $array2[$key]);
            else
                @$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
        }
        return $array1;
    }
    
    0 讨论(0)
提交回复
热议问题