-5

I just want to group this arrays from this:

["2019 Honda Civic" => "Sedan", 
 "Maruti Suzuki Baleno" => "Hatchback",  
 "Rolls-Royce Phantom" => "Sedan"]

to this

["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);
Qirel
  • 25,449
  • 7
  • 45
  • 62

2 Answers2

1

There's probably a combination of array_* functions that could achieve this as well, but you could just loop the array, and flip the values - grouping by the old value (new key), as shown below.

$result = [];
foreach ($array as $k=>$v) {
    if (!isset($result[$v]))
        $result[$v] = [$k];
    else 
        $result[$v][] = $k;
}
return $result;
Qirel
  • 25,449
  • 7
  • 45
  • 62
1

You can easily flip your array with array_flip() and then do a little housekeeping. Check out a demo here: 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));
gutenmorgenuhu
  • 2,312
  • 1
  • 19
  • 33