将现有数组中的 key/value 对翻转为关联数组,该数组允许 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;
}