【发布时间】:2017-01-06 05:38:06
【问题描述】:
手头的 PHP 实验室
实现一个 groupByOwners 函数:
接受一个关联数组,其中包含每个文件名的文件所有者名称。 返回一个关联数组,其中包含每个所有者名称的文件名数组,顺序不限。
例如,对于关联数组["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"] the groupByOwners function should return ["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]。
我已经完成了,我只是在使用 array_merge() 时遇到了问题,以及如何为第二个文件所有者扩展行。
这是我的代码:
<?php
class FileOwners {
public static function groupByOwners($files) {
$i = 0;
$totalOwners=0;
$lastOwners[0] = 0;
$ownerFiles = array();
//input associative array.
foreach ($files as $file => $currentOwner) {
//echo $currentOwner.':'.$file;
// if the last owner checked matches the current, do not backup the owner name.
if ($currentOwner == $lastOwners[$i]) {
//subtract count of how many owners are found by 1.
$totalOwners=$totalOwners-1;
} else {
//Backup the the new owner found.
$namesOfOwners[$i]=$currentOwner;
};
$i++;
$totalOwners++;//count total owners.
$lastOwners[$i] = $currentOwner;
}
$i=0;
$fileCount=0;
// for all owners found (2) test case
foreach ($namesOfOwners as $ownerName) {
//match there own files to there respective arrays, in the order of 0-?
foreach ($files as $file => $currentOwner) {
// if file is matching the current owner and,
if ($ownerName == $currentOwner) {
echo $file.$ownerName;
$ownerFiles[$ownerName] = $file;
}
}
$i++;
}
return print_r($ownerFiles);
}
}
$files = array(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy",
);
var_dump(FileOwners::groupByOwners($files));
问题就在这里。
foreach ($files as $file => $currentOwner) {
// if file is matching the current owner and,
if ($ownerName == $currentOwner) {
echo $file.$ownerName;
$ownerFiles[$ownerName] = $file;
}
}
如果您在上面阅读,问题是我正在尝试使用 array_merge() 将关联数组与字符串合并但是它只支持数组,我希望我的输出为:
["Randy" => ["Input.txt", "Output.txt"] "斯坦" => ["Code.py"]]`
顺序无关紧要,我只是为了自己的教育利益而做实验室。
【问题讨论】:
-
欢迎来到 StackOverflow。请访问help center 并阅读How to Ask。看起来像“请为我修复我的代码”的问题几乎没有解释什么不起作用以及你做了什么,通常会被否决并被搁置为题外话。
标签: php html arrays array-merge