开发者

PHP replace associative array ID values with Name values from another array [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How can I merge PHP arrays?

I have two arrays, both results of db queries. I have a simple example below (no the real data- just for demo purposes. The real data is significantly more complex).

$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 Sm开发者_如何学JAVAith )
)

My question is: how can I match the $persons[name] to replace $results[id] so that I end up with:

$results:

    Array 
    ( [0] => 
      Array ( [id] => John Smith [age] => 29 )
      [1] =>
      Array ( [id] => Jack Jones [age] => 38 )
    )

the arrays are unorderd - I need to replace values if the keys match (and yes, each key in $results definitely has a corresponding entry in $persons). Any help much appreciated!


$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜