Php 如何按特定值对数组进行分组?

Php 如何按特定值对数组进行分组?,php,Php,我有这样一个数组: $files = array( "Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy" ); [ "Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"] ] <?php class FileOwners { public static f

我有这样一个数组:

$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
[
    "Randy" => ["Input.txt", "Output.txt"], 
    "Stan" => ["Code.py"]
]
<?php 
class FileOwners 
{
   public static function groupByOwners($files)
   {
       foreach ($files as $file => $owner){
          $data[$owner] = $file;
       };
       return $data;
   }
}
$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
var_dump(FileOwners::groupByOwners($files));
我想按文件所有者对文件进行分组,并按如下方式返回:

$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
[
    "Randy" => ["Input.txt", "Output.txt"], 
    "Stan" => ["Code.py"]
]
<?php 
class FileOwners 
{
   public static function groupByOwners($files)
   {
       foreach ($files as $file => $owner){
          $data[$owner] = $file;
       };
       return $data;
   }
}
$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
var_dump(FileOwners::groupByOwners($files));
我试着这样做:

$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
[
    "Randy" => ["Input.txt", "Output.txt"], 
    "Stan" => ["Code.py"]
]
<?php 
class FileOwners 
{
   public static function groupByOwners($files)
   {
       foreach ($files as $file => $owner){
          $data[$owner] = $file;
       };
       return $data;
   }
}
$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
var_dump(FileOwners::groupByOwners($files));

请帮助如何创建它。

如果要覆盖$data,请使用
$data[$owner][]=$file
而不是
$data[$owner]=$file

public static function groupByOwners($files)
   {
       foreach ($files as $file => $owner){
          $data[$owner][] = $file;
       };
       return $data;
   }

只需创建一个多维数组
[]

foreach ($files as $file => $owner){
      $data[$owner][] = $file; // [] will store values as an array inside the key
} // Remove semicolon from here