简体   繁体   English

将键/值对从现有数组翻转到关联数组,该数组允许PHP中具有多个值的键

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

I need to basically flip an existing associate array into another associate array. 我基本上需要将现有的关联数组翻转为另一个关联数组。 It needs to contain the keys from the previous array as values and the values of the previous array as keys. 它需要包含前一个数组的键作为值,而前一个数组的值作为键。 Also, it needs to be able to contain multiple values for a single key. 同样,它需要能够为单个键包含多个值。

Code: 码:

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

The output generated is to be: 生成的输出为:

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

You didn't show an attempt but I'm bored: 您没有尝试,但我很无聊:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM