简体   繁体   English

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

[英]PHP Array Merge two Arrays with the same value

I'm new to PHP, and I'm trying to merge the following two arrays into one array, matching the same CODE value: 我是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
        )
)

and

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
        )
)

into this new array: 进入这个新阵列:

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

As you can see, only CODE25 matches on both arrays. 如您所见,两个阵列上只有CODE25匹配。 How do I fix it? 我如何解决它?

$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; }));

We could do this with less code by using native PHP functions, but instead of that and because you're learning, let's try a very basic way: 我们可以通过使用本机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]
            );
    }
}

Disclaimer: this is not a very efficient algorithm. 免责声明:这不是一个非常有效的算法。 But for a short amount of data ( $array1 and $array2 < 20,000 keys each), it will do the trick with no pain. 但是对于少量数据(每个$array1$array2 <20,000个键),它可以毫不费力地完成任务。 See Big O notation for more informations about that. 有关更多信息,请参阅Big O表示法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM