将键/值对从现有数组转换为关联数组,从而允许PHP中的键具有多个值


Flip key/value pairs from an existing array into an associate array which allows for keys with multiple values in PHP

我基本上需要将现有的关联数组翻转到另一个关联数组。它需要将前一个数组中的键作为值,并将前一个数组中的值作为键。此外,它还需要能够为单个键包含多个值。

代码:

 class Owner {
 public static function groupOwners($array)
 {
   //insert code
 }
 }
 $array = array(
  "Input.txt" => "Bob",
  "Code.py" => "Steve",
  "Output.txt" => "Bob"
 );
 var_dump(Owner::groupOwners($array));

生成的输出为:

["Bob"] => ["Input.txt, Output.txt"], ["Steve"] => ["Code.py"]

你没有表现出尝试,但我很无聊:

foreach($array as $key => $val) {
    $result[$val][] = $key;
}