user1092780
user1092780

Reputation: 2447

Merging PHP arrays to form a multidimensional array

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

Upvotes: 1

Views: 3494

Answers (2)

Wes Crow
Wes Crow

Reputation: 2967

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

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270609

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.

Upvotes: 3

Related Questions