1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.