Merge and group by several arrays

前端 未结 3 1970
陌清茗
陌清茗 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:32

    You can use a RecursiveArrayIterator

    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($paths));
    foreach ($iterator as $path => $value) {
        $summed[$path] = isset($summed[$path]) ? $summed[$path] + $value : $value;
    }
    print_r($summed);
    

    or array_walk_recursive and a Closure

    $summed = array();
    array_walk_recursive($paths, function($value, $path) use (&$summed) {
        $summed[$path] = isset($summed[$path]) ? $summed[$path] + $value : $value;
    });
    

    Both will give

    Array
    (
        [/path/file.jpg] => 4
        [/path/file2.bmp] => 3
        [/file3.gif] => 5
    )
    

提交回复
热议问题