我只想从这个分组数组:
["2019 Honda Civic" => "Sedan",
"Maruti Suzuki Baleno" => "Hatchback",
"Rolls-Royce Phantom" => "Sedan"]
对此
["Sedan" => ["2019 Honda Civic", "Rolls-Royce Phantom"],
"Hatchback" => ["Maruti Suzuki Baleno"]]
<?php
function groupByType($cars) {
return;
}
$cars= ["2019 Honda Civic" => "Sedan", "Maruti Suzuki Baleno" => "Hatchback", "Rolls-Royce Phantom" => "Sedan"];
$groups = groupByType($cars);
var_dump($groups);
答案 0 :(得分:1)
可能还有array_*
个函数的组合也可以实现此目的,但是您可以循环数组并翻转值-按旧值(新键)分组,如下所示。
$result = [];
foreach ($array as $k=>$v) {
if (!isset($result[$v]))
$result[$v] = [$k];
else
$result[$v][] = $k;
}
return $result;
答案 1 :(得分:1)
您可以轻松地使用array_flip()翻转阵列,然后做一些整理工作。 在此处查看演示:https://eval.in/1091512
$cars= ["2019 Honda Civic" => "Sedan", "Maruti Suzuki Baleno" => "Hatchback", "Rolls-Royce Phantom" => "Sedan"];
$groups = array_flip($cars);
foreach ($groups as $g => $c)
$groups[$g] = implode(", ", array_keys($cars, $g));