Merge and group by several arrays

给你一囗甜甜゛ 提交于 2019-12-02 07:08:27

one possible way

$rtn = array();
foreach ($array1 as $key=>$val)
{
  $rtn[$key]+=$val;
}

foreach ($array2 as $key=>$val)
{
  $rtn[$key]+=$val;
}

foreach ($array2 as $key=>$val)
{
  $rtn[$key]+=$val;
}

the above will assign the filename, SUM(val) as an associative array into $rtn

[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;
}

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
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!