合并具有共同值的数组

时间:2017-08-09 09:24:42

标签: php arrays sorting

我有两个数组,即arr和arr2。

var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];

var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];

是否可以从上面两个数组中显示下面的数组?

result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];

如果我使用array_merge,那么我得到答案为

result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];

3 个答案:

答案 0 :(得分:2)

您必须将JSON解码为数组,手动合并它们并再次将其编码为JSON:)

<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);

$result = [];
foreach ($arr as &$item) {
    if (empty($arr2))
        break;

    foreach ($arr2 as $key => $item2) {
        if ($item['month'] === $item2['month']) {
            $item = array_merge($item, $item2);
            unset($arr2[$key]);
            continue;
        }
    }
}
if (!empty($arr2))
    $arr = array_merge($arr, $arr2);

echo json_encode($arr);

答案 1 :(得分:1)

第一个想到的函数是array_merge_recursive(),但即使您将临时关联键分配给子数组,最终也会在新的深度子数组中出现多个January值。

但不要绝望,还有另一种可以完成这项工作的递归功能。只要先分配临时关联键,array_replace_recursive()就会成功合并这些多维数组。

这是一个不使用foreach()循环或if语句的单行:

代码:(Demo

$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));

输出:

[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]

细分:

echo json_encode(  // convert back to json
         array_values(  // remove the temp keys (reindex)
             array_replace_recursive(  // effectively merge/replace elements associatively
                 array_column($arr,NULL,'month'),  // use month as temp keys for each subarray
                 array_column($arr2,NULL,'month')  // use month as temp keys for each subarray
             )
         )
     );

答案 2 :(得分:0)

你应该编写自己的函数来做到这一点

$res = [];
foreach ($arr as $item) {
    $res[$item['month']] = $item;
}

foreach ($arr2 as $item) {
    $res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}

var_dump($res);