Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 589
Abaij Avatar asked Nov 19 '25 02:11

Abaij


2 Answers

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;
   }
like image 87
suresh bambhaniya Avatar answered Nov 20 '25 16:11

suresh bambhaniya


Just create a multidimensional array [],

foreach ($files as $file => $owner){
      $data[$owner][] = $file; // [] will store values as an array inside the key
} // Remove semicolon from here
like image 26
Samir Selia Avatar answered Nov 20 '25 16:11

Samir Selia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!