2017-03-18 67 views
0
<?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)); 

功能实现一个groupByOwners功能:如何实现与阵列

  • 接受包含每个文件名的文件所有者名称的关联数组。

  • 以任意顺序返回包含每个所有者名称的文件名数组的关联数组。

    例如

鉴于输入:

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

groupByOwners回报:

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

回答

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

ö输出:

Array 
(
    [Randy] => Array 
     (
      [0] => Input.txt 
      [1] => Output.txt 
     ) 

    [Stan] => Array 
     (
      [0] => Code.py 
     ) 

)