<?php class FileOwners { public static function groupByOwners($files) { return NULL; } } $files = array ( "Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy" ); var_dump(FileOwners::groupByOwners($files));
Implement a groupByOwners function :
Accepts an associative array containing the file owner name for each file name.
Returns an associative array containing an array of file names for each owner name, in any order.
For example
Given the input:
["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"]
groupByOwners returns:
["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]
Advertisement
Answer
<?php class FileOwners { public static function groupByOwners($files) { $result=array(); foreach($files as $key=>$value) { $result[$value][]=$key; } return $result; } } $files = array ( "Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy" ); print_r(FileOwners::groupByOwners($files));
Output:
Array ( [Randy] => Array ( [0] => Input.txt [1] => Output.txt ) [Stan] => Array ( [0] => Code.py ) )