"Randy", "Code.py" => "Stan", "Output.txt" => -6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:15:01 25 4
gpt4 key购买 nike

我有一个这样的数组:

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com