elBrambore
elBrambore

Reputation: 130

Missing values from the same key after using array_flip function

I'm trying to flip array but it missed value from the key with the same name. What do I have to use, to add couple values to key which occur multiple times in array?

For example, for

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

the groupByOwners function should return

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

The current code:

class FileOwners
{
    static $files;
    public static function groupByOwners($files)
    {
       $flip = array_flip($files);
        print_r($flip);
    }
}

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

My function return Array ( [Randy] => Output.txt [Stan] => Code.py ) NULL.

So value "Input.txt" is missing. It has to be the same key for both values, so how can I put "Input.txt" with "Output.txt" in array for key [Randy]?

Upvotes: 2

Views: 1542

Answers (2)

MonkeyZeus
MonkeyZeus

Reputation: 20747

You will have to loop it yourself and build a new array:

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

$new_files = array();

foreach($files as $k=>$v)
{
    $new_files[$v][] = $k;
}

print_r($new_files);

Upvotes: 3

kmdm
kmdm

Reputation: 143

A somewhat quick and a little hacky solution:

php >  $files = array
php >     (
php (         "Input.txt" => "Randy",
php (         "Code.py" => "Stan",
php (         "Output.txt" => "Randy"
php (     );
php > var_dump(array_reduce(array_keys($files), function($p, $c) use (&$files) { $p[$files[$c]] = $p[$files[$c]] ?? []; $p[$files[$c]][] = $c; return $p;  }, []));
array(2) {
  ["Randy"]=>
  array(2) {
    [0]=>
    string(9) "Input.txt"
    [1]=>
    string(10) "Output.txt"
  }
  ["Stan"]=>
  array(1) {
    [0]=>
    string(7) "Code.py"
  }
}

NB: The use of '??' requires PHP 7.0.

Just to pull the important part out of the one-liner and make it at least slightly more readable:

array_reduce(array_keys($files), function($p, $c) uses (&$files) {
     $p[$files[$c]] = $p[$files[$c]] ?? []; 
     $p[$files[$c]][] = $c;
}, []);

You could just as easily use the if(isset(...)) logic to ensure the array element in $p exists.

Upvotes: 0

Related Questions