我有一个数组,看起来像这样:
[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
)
我尝试将这个数组分组到一个新的多维数组结构中,以便它输出如下内容:
Continent
- Country Name
-- Cities under Every Country
确切的预期结果:
array (
'Latin America' =>
array (
'Venezuela' =>
array (
0 => 'Caracas',
),
),
'Middle East' =>
array (
'Egypt' =>
array (
0 => 'Cairo',
),
'United Arab Emirates' =>
array (
0 => 'Abu Dhabi',
1 => 'Dubai',
),
),
'North America' =>
array (
'Canada' =>
array (
0 => 'Montreal',
),
),
)
4条答案
按热度按时间6xfqseft1#
wgeznvg72#
还有几种替代方法:
在无主体的
foreach()
中使用“数组解构”来填充分层结构(Demo)(Further about the technique)使用
array_reduce()
避免在全局范围内声明结果变量。(Demo)8fsztsew3#
那么这个解决方案呢:
lrpiutwd4#
我认为你只需要在你的数组中循环,然后创建一个新的数组,使用一些值作为键,另一些值作为值,例如
Live Sample