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 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"
}

请帮助如何制作它。

最佳答案

你正在覆盖 $data,使用 $data[$owner][] = $file; 而不是 $data[$owner]= $file;

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

关于php - 如何按特定值对数组进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277290/

相关文章:

php - 混合使用 Python 和 PHP?

php - 对数组进行排序 - 数字、特殊字符、字母

php - 只允许在 Woocommerce 3 中购买一件商品

php - LswMemcacheBundle 中的缓存生命周期

php - select count() 查询中的 limit 子句未按我的预期工作

php - 通过 CLI 运行 Codeigniter 输出网站根目录而不是预期结果

javascript - 如何通过 AJAX 使用 AWS Polly PHP SDK 在 HTML5 音频播放器中进行流式传输

php - 通过调用另一个函数设置函数中的静态变量

php - PDO 取最大值

javascript - PHP数组查找元素错误