【发布时间】:2018-05-14 11:51:43
【问题描述】:
我正在尝试翻转数组,但它错过了同名键的值。 我必须使用什么来向数组中多次出现的键添加几个值?
例如,对于
[
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
]
groupByOwners 函数应该返回
[
"Randy" => ["Input.txt", "Output.txt"],
"Stan" => ["Code.py"]
]
当前代码:
class FileOwners
{
static $files;
public static function groupByOwners($files)
{
$flip = array_flip($files);
print_r($flip);
}
}
$files = array
(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
);
我的函数返回Array ( [Randy] => Output.txt [Stan] => Code.py ) NULL。
因此缺少“Input.txt”值。这两个值必须是相同的键,那么如何将“Input.txt”和“Output.txt”放在键[Randy]的数组中?
【问题讨论】:
-
欢迎来到 SO!好问题。您应该始终提供的一件事是期望的输出(类似于您提供
$files的方式)。答案可能会有所不同,具体取决于 all 数组元素是否可以成为值数组。 -
@cale_b 有点隐藏但是“groupByOwners 函数应该返回
["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]”
标签: php arrays function oop array-flip