问题描述
假设我有以下数组:
Array ( [0] => Array ( [id] => 5 [name] => Education ) [1] => Array ( [id] => 4 [name] => Computers ) [3] => Array ( [id] => 7 [name] => Science [4] => Array ( [id] => 1 [name] => Sports ) )
第二个:
Array ( [0] => Array ( [id] => 1 [title] => Sport ) [1] => Array ( [id] => 7 [title] => Sci ) [3] => Array ( [id] => 4 [title] => Comp [4] => Array ( [id] => 5 [title] => Edu ) )
所需的输出是:
Array ( [0] => Array ( [id] => 5 [name] => Education [title] => Edu ) [1] => Array ( [id] => 4 [name] => Computers [title] => Comp ) [3] => Array ( [id] => 7 [name] => Science [title] => Sci [4] => Array ( [id] => 1 [name] => Sports [title] => Sport ) )
我已经设法将这些数组与简单地合并:
I have managed to merge these arrays with simply:
foreach($first as $key => $value){ $result[$key] = array_merge($first[$key], $second[$key]); }
但是输出没有正确组合:
But the output is not combined correctly:
Array ( [0] => Array ( [id] => 5 [name] => Education [title] => Sport ) [1] => Array ( [id] => 4 [name] => Computers [title] => Sci ) [3] => Array ( [id] => 7 [name] => Science [title] => Comp [4] => Array ( [id] => 1 [name] => Sports [title] => Edu ) )
问题是我想在相同的 id 上合并这些数组.所需的输出排序应与第一个数组中的排序相同.
The problem is I would like to merge these arrays on the same id. Desired output sorting should be same as in the first array.
我怎样才能做到这一点?非常感谢任何帮助.
How can I achieve this? Any help is much appreciated.
推荐答案
你可以做一个嵌套循环并检查 id 值是否匹配,然后将 title 添加到$first(或 name 到 $second)
You can just do a nested loop and check if the id values match, then add title to $first (or name to $second)
foreach($first as $key => $value){ foreach($second as $value2){ if($value['id'] === $value2['id']){ $first[$key]['title'] = $value2['title']; } } }