phparraysmultidimensional-arraytranspose

How to convert multiple flat arrays into a 2d array with values grouped by shared index?


I'm teaching myself PHP and I have the following question about arrays:

I have:

$names = array('John', 'Alice', 'Tom');
$cities = array('London', 'NY', 'Boston');
$years = array('1999', '2010', '2012');
$colors = array('red', 'blue', 'green'); 

I want to have a new array with these elements (three subarrays):

 John London 1999 red
 Alice NY 2010 blue
 Tom Boston 2012 green 

I'm doing

 $newArray = array($names,$cities, $years,$colors);

But this shows all the names, cities and so all together :( Please show me how to achieve this.

Thanks a lot!


Solution

  • If You want the three list to be arrays with each value an element in a sub array, do this:

    $names = array('John', 'Alice', 'Tom');
    $cities = array('London', 'NY', 'Boston');
    $years = array('1999', '2010', '2012');
    $colors = array('red', 'blue', 'green'); 
    
    $final_array = array();
    
    foreach($names as $count => $name){
        array_push($final_array,array($name,$cities[$count],$years[$count],$colors[$count]));
    }
    
    var_export($final_array);
    

    This gives an output of:

    array (
      0 => 
      array (
        0 => 'John',
        1 => 'London',
        2 => '1999',
        3 => 'red',
      ),
      1 => 
      array (
        0 => 'Alice',
        1 => 'NY',
        2 => '2010',
        3 => 'blue',
      ),
      2 => 
      array (
        0 => 'Tom',
        1 => 'Boston',
        2 => '2012',
        3 => 'green',
      ),
    

    If you want the result to be an array of strings use Mihai's answer.