我在PHP(Codeigniter)中有如下所示的数组。我想使用国家/地区名称对它们进行分组。所以country键的值将成为外部数组的关键
Array
(
[0] => Array
(
[city] => Buenos Aires
[country] => Argentina
)
[1] => Array
(
[city] => Adelaide
[country] => Australia
)
[2] => Array
(
[city] => Brisbane
[country] => Australia
)
[3] => Array
(
[city] => Fremantle
[country] => Australia
)
[4] => Array
(
[city] => Melbourne
[country] => Australia
)
[5] => Array
(
[city] => Sydney
[country] => Australia
)
)
我想将其转换为如下所示的数组,因此国家/地区将成为按照国家/地区名称列入城市列表的关键
Array
(
[Argentina] => Array
(
[0] => Buenos Aires
)
[Australia] => Array
(
[0] => Adelaide
[1] => Brisbane
[2] => Melbourne
[3] => Sydney
)
)
答案 0 :(得分:1)
这是代码,
$arr = [//your arr];
$result = []; // will be your output
foreach($arr as $k => $v){
$result[$v['country']][] = $v['city'];
}
我希望这会起作用