0

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 Smith )
)

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!

5
  • See the answer to the duplicate: stackoverflow.com/questions/25147/how-can-i-merge-php-arrays Commented Jun 22, 2011 at 15:54
  • I Tried the final answer in that post but doesn't seem to work. I think it is a little more tricky with a multi-dimensional array. Commented Jun 22, 2011 at 16:09
  • @user791335 -- that example is basically the same as the dupes.. Commented Jun 22, 2011 at 16:10
  • I have to admit I am still struggling. I have tried variations on the answers provided, but not getting the results I want, I think principally because of them being multi-dimensional arrays. I would really appreciated any further pointers. Commented Jun 22, 2011 at 16:32
  • @user that example is the exact same thing as your question, except it is merged by id and yours is by name (which you should probably switch) Commented Jun 22, 2011 at 16:34

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.