如何将关联数组与下一个迭代变量合并?

How to merge an associative array with the next iterating var?

手边的 PHP 实验室

实现一个 groupByOwners 函数:

接受包含每个文件名的文件所有者名称的关联数组。 Returns 包含每个所有者名称的文件名数组的关联数组,顺序不限。

例如,对于关联数组 ["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"] "Stan" => ["Code.py"]]`

顺序都不重要,我只是为了自己的教育利益而做实验。

我发现您编写的代码有两个问题:

1) Return groupByOwners() 函数的语句。 print_r() 将 return 布尔值,因此 var_dump() 永远不会输出您需要的数组。

return print_r($ownerFiles);

应该是

return $ownerFiles;

2) 你在问题中指出并提到的那个。不更新值,而是将 $file 变量插入 $ownerFiles[$ownerName] 数组:-

$ownerFiles[$ownerName] = $file;     

应该是

$ownerFiles[$ownerName][] = $file;