Merge and group by several arrays

前端 未结 3 1943
陌清茗
陌清茗 2021-01-24 03:55

I need to merge associative arrays and group by the name. Say I have such 3 arrays:

ARRAY1
    \"/path/file.jpg\"  =>  2, 
    \"/path/file2.bmp\" =>  1,
          


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 04:38

    [EDIT: I adapted the function (as suggested by John Green) to use func_get_args so you don't need to put all the seperate arrays in one array before you can use it.]

    I think you could use the following function.

    mergeArrays()
    {
        $return = array();
        $arrays = func_get_args();
        foreach ($arrays as $array) {
            foreach ($array as $key => $val) {
                if (array_key_exists($key, $array) {
                    $return[$key] += $val;
                } else {
                    $return[$key] = $val;
                }
            }
        }
        return $return;
    }
    

提交回复
热议问题