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

后端 未结 2 500
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 21:13

So I have an array that looks like this:

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

[99         


        
相关标签:
2条回答
  • 2020-12-06 21:55

    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

    0 讨论(0)
  • 2020-12-06 22:07
    $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);
    
    0 讨论(0)
提交回复
热议问题