如何使用数组

时间:2017-03-18 03:39:56

标签: 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));

实施groupByOwners功能:

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

  • 以任意顺序返回包含每个所有者名称的文件名数组的关联数组。

    例如

鉴于输入:

["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"]

groupByOwners返回:

["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]

2 个答案:

答案 0 :(得分:4)

<?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));

<强>输出:

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

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

)

答案 1 :(得分:0)

这是一个肯定可以工作的女巫:

 function groupByOwners(array $files) : array
 {
$result =array();
foreach($files as $key =>$elem){
  $result[$elem][]=$key;
 }
return $result;
    }
$files = array
(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
 );
  var_dump(groupByOwners($files));