I have the following two arrays:

Array ( [Jonah] => 27 [Bianca] => 32

Array ( [Jonah] => 2 [Bianca] => 7

Is it possible to merge them together to form a multidimensional array in this format?

Array ( [0] => Array 
               ( [name] => Jonah 
                 [age] => 27 
                 [number] => 2 )
        [1] => Array 
               ( [name] => Bianca 
                 [age] => 32 
                 [number] => 7 )
      )
link|improve this question

what did you try? – Cfreak Feb 11 at 22:46
feedback

2 Answers

up vote 2 down vote accepted

A temporary array keyed by name stores the values from the first two arrays. The temporary array is then copied to a final array keyed numerically:

$arr1 = array ( 'Jonah' => 27, 'Bianca' => 32 );
$arr2 = array ( 'Jonah' => 2, 'Bianca' => 7 );

$tmp = array();

// Using the first array, create array keys to $tmp based on
// the name, and holding the age...
foreach ($arr1 as $name => $age) {
 $tmp[$name] = array('name' => $name, 'age' => $age);
}

// Then add the number from the second array
// to the array identified by $name inside $tmp
foreach ($arr2 as $name => $num) {
  $tmp[$name]['number'] = $num;
}

// Final array indexed numerically:
$output = array_values($tmp);
print_r($output);

Array
(
    [0] => Array
        (
            [name] => Jonah
            [age] => 27
            [number] => 2
        )

    [1] => Array
        (
            [name] => Bianca
            [age] => 32
            [number] => 7
        )

)

Note: The last step of copying the array to make it numerically isn't strictly needed, if you're ok with your output array being keyed by name. In that case, $tmp is the final product.

link|improve this answer
Thanks so much, works perfectly! – user1092780 Feb 11 at 23:06
feedback

OK. The following functionality should get you were you want to be:

$people = array ( 'Jonah' => 27, 'Bianca' => 32 );
$numbers = array ( 'Jonah' => 2, 'Bianca' => 7 );
$merged = array();
$i = 0;

foreach ($people as $k=>$v)
{
   if (isset($numbers[$k]))
   {
      $merged[$i]['name'] = $k;
      $merged[$i]['age'] = $v;
      $merged[$i++]['number'] = $numbers[$k];
   }
}

Now, if you do a var_dump($merged); you will get:

array
  0 => 
    array
      'name' => string 'Jonah' (length=5)
      'age' => int 27
      'number' => int 2
  1 => 
    array
      'name' => string 'Bianca' (length=6)
      'age' => int 32
      'number' => int 7
link|improve this answer
Thanks so much, works perfectly! – user1092780 Feb 11 at 23:05
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.