如何用数组实现函数

Sur*_*eti 2 php

<?php
class FileOwners
{
    public static function groupByOwners($files)
    {
        return NULL;
    }
}

$files = array
(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);

var_dump(FileOwners::groupByOwners($files));
Run Code Online (Sandbox Code Playgroud)

实现 groupByOwners 函数:

  • 接受包含每个文件名的文件所有者名称的关联数组。

  • 返回一个关联数组,其中包含以任何顺序排列的每个所有者名称的文件名数组。

    例如

鉴于输入:

["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"]
Run Code Online (Sandbox Code Playgroud)

groupByOwners 返回:

["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]
Run Code Online (Sandbox Code Playgroud)

Sah*_*ati 5

<?php
class FileOwners
{
    public static function groupByOwners($files)
    {
        $result=array();
        foreach($files as $key=>$value)
        {
            $result[$value][]=$key;
        }
        return $result;
    }
}

$files = array
(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
print_r(FileOwners::groupByOwners($files));
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [Randy] => Array
        (
            [0] => Input.txt
            [1] => Output.txt
        )

    [Stan] => Array
        (
            [0] => Code.py
        )

)
Run Code Online (Sandbox Code Playgroud)