[英]PHP array search - How to find the match of the key of an array in another array?
如何在另一個數組中找到數組鍵的匹配項 ?
例如,
陣列1
Array
(
[0] => Array
(
[parent_id] => 4 // the lookup key
[count] => 7
)
[1] => Array
(
[parent_id] => 5 // the lookup key
[count] => 2
)
)
陣列2
Array
(
[0] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
)
[1] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
[parent_id] => 4 // the match
)
[2] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
)
[3] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
[parent_id] => 5 // the match
)
[4] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
)
)
結果是我追求
Array
(
[0] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
[parent_id] => 4
[count] => 7
)
[1] => Array
(
[router] => xxx
[path] => xxx
[plugin] => xxx
[parent_id] => 5
[count] => 2
)
)
嘗試這個 ..
array_column函數將從第二個數組返回parent_id,array_search函數將匹配array1和array2的兩個parent_id,而array_merge函數會將兩個數組與匹配的parent_id合並。
未經測試,因此請原諒任何小的語法錯誤。
$array1 = array(); // this is your first array in your example
$array2 = array(); // this is your second array in your example
$result = array(); // this is what you're looking for
foreach ($array1 as $row) {
$result[] = array_merge($row, $array2[array_search($row["parent_id"], array_column($array2,"parent_id")];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.