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

时间:2018-11-13 09:03:58

标签: 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 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));

但是我得到的是这个

array(2) {
    ["Randy"]=>string(10) "Output.txt",
    ["Stan"]=>string(7) "Code.py"
}

请帮助如何制作。

2 个答案:

答案 0 :(得分:5)

您要覆盖$ data,请使用$data[$owner][] = $file;代替$data[$owner]= $file;

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

答案 1 :(得分:2)

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

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