关联数组值可以是数组

时间:2017-06-13 04:30:44

标签: php

这是一个我无法用php解决的简单问题。我想将第一个数组转换为这样的类:["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);
  }
}
第6行的

$element = $value =>[];是我直观的解决方案,但无效。

我是否使用了糟糕的模式,这是不可取的?根据{{​​3}},"值可以是任何类型。"

2 个答案:

答案 0 :(得分:5)

你可以做 -

$array = ["F1" => "Mercedes", "g3"=>"BMW", "g4"=>"BMW"];
$newArray = [];

foreach($array as $key => $value) {
    $newArray[$value][] = $key;
}

print_r($newArray);

<强>输出

Array
(
    [Mercedes] => Array
        (
            [0] => F1
        )

    [BMW] => Array
        (
            [0] => g3
            [1] => g4
        )

)

对于您希望添加ksort($newArray);

的订单

输出将是 -

Array
(
    [BMW] => Array
        (
            [0] => g3
            [1] => g4
        )

    [Mercedes] => Array
        (
            [0] => F1
        )

)

ksort()

Demo

答案 1 :(得分:0)

试试这个。

<?php
$array = ["F1" => "Mercedes", "g3"=>"BMW", "g4"=>"BMW"];
$newArray = [];

foreach($array as $key=>$value){
$newArray[$value][]=$key;
}
echo "<pre>";
print_r($newArray);
exit;
?>