phparraysgroupingassociative-arrayarray-flip

Flip an associative array and prevent losing new values from new key collisions


I have an array like this:

$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);

I want to group the file by its owner and returned like this:

[
    "Randy" => ["Input.txt", "Output.txt"], 
    "Stan" => ["Code.py"]
]

I tried to do it like this:

<?php 
class FileOwners 
{
   public static function groupByOwners($files)
   {
       foreach ($files as $file => $owner){
          $data[$owner] = $file;
       };
       return $data;
   }
}
$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
var_dump(FileOwners::groupByOwners($files));

But what I got is this:

array(2) {
    ["Randy"]=>string(10) "Output.txt",
    ["Stan"]=>string(7) "Code.py"
}

Please help how to make it.


Solution

  • you are overriding $data, use $data[$owner][] = $file; instead of $data[$owner]= $file;

    public static function groupByOwners($files)
       {
           foreach ($files as $file => $owner){
              $data[$owner][] = $file;
           };
           return $data;
       }