How to convert a Single Array into a multidimensional array in PHP?

So I have an array that looks like this:

[98] => Array
(
    [City] => Caracas
    [Country] => Venezuela
    [Continent] => Latin America
)

[99] => Array
(
    [City] => Cairo
    [Country] => Egypt
    [Continent] => Middle East
)

[105] => Array
(
    [City] => Abu Dhabi
    [Country] => United Arab Emirates
    [Continent] => Middle East
)

[106] => Array
(
    [City] => Dubai
    [Country] => United Arab Emirates
    [Continent] => Middle East
)

[107] => Array
(
    [City] => Montreal
    [Country] => Canada
    [Continent] => North America
)

I am trying to sort this array into a multi-dimensional array, so that it outputs something like:

Continent
    - Country Name    
      -- Cities under Every Country

I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$array = array(
    98 => array(
        'City' => 'Caracas',
        'Country' => 'Venezuela',
        'Continent' => 'Latin America',
    ),
    99 => array(
        'City' => 'Cairo',
        'Country' => 'Egypt',
        'Continent' => 'Middle East',
    ),
    105 => array(
        'City' => 'Abu Dhabi',
        'Country' => 'United Arab Emirates',
        'Continent' => 'Middle East',
    ),
    106 => array(
        'City' => 'Dubai',
        'Country' => 'United Arab Emirates',
        'Continent' => 'Middle East',
    ),
    107 => array(
        'City' => 'Montreal',
        'Country' => 'Canada',
        'Continent' => 'North America',
    )
);

$newArray = array();
foreach ($array as $row)
{
   $newArray[$row['Continent']][$row['Country']][] = $row['City'];
}

print_r($newArray);

Solution 2

I think you just need to loop in your array and create a new one using some values as keys and some other as value, for example

$new_array = array();
foreach($array as $val)
{ 
     $new_array[$val['Continent']][$val['Country']] = array('City' => $val['City']);
}  

Live Sample

Solution 3

What about this solution:

function arrayToMultiDimensionalArray(array $elements, array $dimensions)
{
    $output = [];

    foreach ($elements as $element) {
        $outputElement =& $output;

        foreach ($dimensions as $dimension) {
            $outputElement =& $outputElement[$element[$dimension]];
        }

        $outputElement[] = $element;
    }

    return $output;
}

$dimensions = ['Continent', 'Country'];

$tree = arrayToMultiDimensionalArray($array, $dimensions);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply