假设我有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(),但它只是在不比较键的情况下合并数组。
答案 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"]
)
);