2017-03-18 27 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 
     ) 

)