PHP数组合并两个具有相同值的数组

时间:2014-02-07 02:47:15

标签: php arrays

我是PHP的新手,我正在尝试将以下两个数组合并为一个数组,匹配相同的CODE值:

Array(1)
(
    [0] => Array
        (
            [0] => CODE11
            [1] => NAME
            [2] => ADDRESS
        )
    [1] => Array
        (
            [0] => CODE23
            [1] => NAME
            [2] => ADDRESS
        )
    [2] => Array
        (
            [0] => CODE25
            [1] => NAME
            [2] => ADDRESS
        )
)

Array(2)
(
    [0] => Array
        (
            [0] => CODE43
            [1] => CITY
            [2] => COUNTRY
        )
    [1] => Array
        (
            [0] => CODE25
            [1] => CITY
            [2] => COUNTRY
        )
    [2] => Array
        (
            [0] => CODE89
            [1] => CITY
            [2] => COUNTRY
        )
)

进入这个新阵列:

Result
(
    [0] => Array
        (
            [0] => CODE25
            [1] => NAME
            [2] => ADDRESS
            [3] => CITY
            [4] => COUNTRY
        )
)

如您所见,两个阵列上只有CODE25匹配。我该如何解决?

2 个答案:

答案 0 :(得分:2)

$hash = array();
// First create an associative array from $array1 using the CODE as the key
foreach ($array1 as $el) {
    $hash[$el[0]] = $el;
}
// Then append the data from $array2 to matching elements
foreach ($array2 as $el) {
    if (isset($hash[$el[0]])) {
        $hash[$el[0]] = array_merge($hash[$el[0]], array_slice($el, 1));
    }
}
// Now find the elements that were matched and return them as an ordinary array
$new_array = array_values(array_filter($hash, function($x) { return count($x) > 3; }));

答案 1 :(得分:0)

我们可以通过使用本机PHP函数来减少代码,但不是这样,因为你正在学习,让我们尝试一种非常基本的方法:

foreach ($array1 as $key1 => $value1)
{
    foreach ($array2 as $key2 => $value2)
    {
        if ($value1[0] == $value2[0])
            $result[] = array(
                $value1[0],
                $value1[1],
                $value1[2],
                $value2[1],
                $value2[2]
            );
    }
}

免责声明:这不是一个非常有效的算法。但是对于少量数据(每个$array1$array2 <20,000个键),它可以毫不费力地完成任务。有关更多信息,请参阅Big O notation