我有两个数组,都是数据库查询的结果。我在下面有一个简单的例子(没有真正的数据 - 仅用于演示目的。实际数据要复杂得多)。
$results:
Array
( [0] =>
Array ( [id] => 20 [age] => 29 )
[1] =>
Array ( [id] => 593 [age] => 38 )
)
$persons:
Array
( [0] =>
Array ( [id] => 593 [name] => Jack Jones )
[1] =>
Array ( [id] => 20 [name] => John Smith )
)
我的问题是:如何匹配$ persons [name]来替换$ results [id],以便我最终得到:
$results:
Array
( [0] =>
Array ( [id] => John Smith [age] => 29 )
[1] =>
Array ( [id] => Jack Jones [age] => 38 )
)
数组是无序的 - 如果键匹配,我需要替换值(是的,$ results中的每个键肯定在$ persons中有相应的条目)。任何帮助非常感谢!
答案 0 :(得分:1)
$a = array(
array('id'=>58,'name'=>'name1'),
array('id'=>63,'name'=>'name2'),
);
$b = array(
array('id'=>63,'value'=>'value2'),
array('id'=>58,'value'=>'value1'),
);
//making key-value
foreach(array_values($a) as $tmp)
{
$aProcessed[$tmp['id']]=$tmp['name'];
}
foreach(array_values($b) as $tmp)
{
$bProcessed[$tmp['id']]=$tmp['value'];
}
//uncomment to see key-value arrays
//var_dump($aProcessed,$bProcessed);
//combining
foreach($aProcessed as $key=>$value)
{
$result[]=array('name'=>$aProcessed[$key],'value'=>$bProcessed[$key]);
}
var_dump($result);