Reputation:
Here is a simple problem that I was unable to solve with php.I want to convert the first array to something like this: ["BMW"=>["g4","g3"], "Mercedes"=>["f1"]]
$array = ["F1" => "Mercedes", "g3"=>"BMW", "g4"=>"BMW"];
$newArray = [];
foreach($array as $key=>$value){
if(!in_array($value, $newArray){
$element = $value => [$key];
array_push($newArray, $element);
} else {
array_push($newArray[$value],$key);
}
}
$element = $value =>[];
on line 6 was my intuitive solution but is invalid.
Am I using a poor pattern, is this inadvisable? According to official documentation, "The value can be of any type."
Upvotes: 0
Views: 59
Reputation: 1703
Try this.
<?php
$array = ["F1" => "Mercedes", "g3"=>"BMW", "g4"=>"BMW"];
$newArray = [];
foreach($array as $key=>$value){
$newArray[$value][]=$key;
}
echo "<pre>";
print_r($newArray);
exit;
?>
Upvotes: 0
Reputation: 31749
You can simply do -
$array = ["F1" => "Mercedes", "g3"=>"BMW", "g4"=>"BMW"];
$newArray = [];
foreach($array as $key => $value) {
$newArray[$value][] = $key;
}
print_r($newArray);
Output
Array
(
[Mercedes] => Array
(
[0] => F1
)
[BMW] => Array
(
[0] => g3
[1] => g4
)
)
For the order you are expecting add ksort($newArray);
The output will be -
Array
(
[BMW] => Array
(
[0] => g3
[1] => g4
)
[Mercedes] => Array
(
[0] => F1
)
)
Upvotes: 5