0

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."

1
  • You can certainly have arrays as entries in arrays, but => can only be used in array initializes, so $element = $value =>[]; is meaningless. Commented Jun 13, 2017 at 5:24

2 Answers 2

5

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
        )

)

ksort()

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

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;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.