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