合并具有共同值的四个数组

时间:2017-08-17 18:10:07

标签: php arrays

我有四个数组,如下所示

$array1 = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$array2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$array3 = json_decode('[{"month":"January","domain":120},{"month":"February","domain":200},{"month":"June","domain":100}]', true);
$array4 = json_decode('[{"month":"January","file":80},{"month":"June","file":10}]')

我的预期输出将是

$result=[{"month":"January","url":1,"ip":12,"domain":120,"file":80},{"month":"February","url":102,"domain":120},{"month":"March","url":192,"domain":120},{"month":"June","ip":10,"domain":100,"file":10}]

我试过这样,我可以得到两个数组。但我无法获得四个阵列。

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

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

echo json_encode($array1);

2 个答案:

答案 0 :(得分:1)

您可以使用next函数从关联数组中获取第二个元素,并使用key函数获取密钥:

$array1 = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$array2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$array3 = json_decode('[{"month":"January","domain":120},{"month":"February","domain":200},{"month":"June","domain":100}]', true);
$array4 = json_decode('[{"month":"January","file":80},{"month":"June","file":10}]', true);

$array5 = array_merge($array1, $array2, $array3, $array4);

$finalArr = [];
foreach ($array5 as $value) {
    $finalArr[$value['month']]['month'] = $value['month'];
    next($value);
    $finalArr[$value['month']][key($value)] = $value[key($value)];
}

echo json_encode(array_values($finalArr), true);

给出:

[{"month":"January","url":1,"ip":12,"domain":120,"file":80},{"month":"February","url":102,"domain":200},{"month":"March","url":192},{"month":"June","ip":10,"domain":100,"file":10}]

答案 1 :(得分:-1)

试试这个

$array1 = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$array2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$array3 = json_decode('[{"month":"January","domain":120},{"month":"February","domain":200},{"month":"June","domain":100}]', true);
$array4 = json_decode('[{"month":"January","file":80},{"month":"June","file":10}]', true);

$result = [];

foreach ( [$array1, $array2, $array3, $array4] as $row )
{
    foreach ( $row as $item )
    {
        $month = $item['month'];
        if ( isset($result[$month]) )
        {
            $item = array_merge($result[$month], $item);
        }

        $result[$month] = $item;
    }
}

var_dump(array_values($result));