按键加入2个数组

时间:2016-03-22 10:33:30

标签: php arrays join merge

假设我有2个数组:

$arr1 = array (
        array (
                "animal" => "cat",
                "color" => "grey" 
        ),
        array (
                "animal" => "dog",
                "color" => "black" 
        ),
        array (
                "animal" => "mouse",
                "color" => "white" 
        ) 
);

$arr2 = array (
        array (
                "title" => "mouse",
                "name" => "Abby" 
        ),
        array (
                "title" => "dog",
                "name" => "Rex" 
        ),
        array (
                "title" => "dog",
                "name" => "Barney" 
        ),
        array (
                "title" => "mouse",
                "name" => "Georgie" 
        ) 
);

我现在想要通过密钥(来自animal的{​​{1}}和来自$arr1的{​​{1}})加入他们,以便我拥有:

title

只需在$arr2中添加$arr1 = array ( array ( "animal" => "cat", "color" => "grey" ), array ( "animal" => "dog", "color" => "black", "name" => "Rex", "name" => "Barney" ), array ( "animal" => "mouse", "color" => "white", "name" => "Abby", "name" => "Georgie" ) ); dog的名称。

我的解决方案是:

mouse

但它覆盖了第一个条目,所以我只得到姓氏:

$arr2

我查看了array_merge(),但它只是在不比较键的情况下合并数组。

1 个答案:

答案 0 :(得分:2)

因此名称索引必须是数组:)

尝试如下

foreach ( $arr1 as $key1 => $entry1 ) {
    foreach ( $arr2 as $key2 => $entry2 ) {
        if ($entry1 ["animal"] == $entry2 ["title"]) {
            if (!isset($arr1[$key1]["name"])) {
                $arr1[$key1]["name"] = array();
            }
            $arr1 [$key1]["name"][] = $entry2 ["name"];
        }
    }
}

<强>输出

$arr1 = array (
            array (
                    "animal" => "cat",
                    "color" => "grey" 
            ),
            array (
                    "animal" => "dog",
                    "color" => "black",
                    "name" => ["Rex", "Barney" ] 
            ),
            array (
                    "animal" => "mouse",
                    "color" => "white",
                    "name" => ["Abby", "Georgie"]
            ) 
);