"Stan", "Output.txt" => "Randy" ); var_dump(FileOwners::groupByOwners-6ren">
gpt4 book ai didi

php - 如何使用数组实现函数

转载 作者:行者123 更新时间:2023-12-03 20:26:16 24 4
gpt4 key购买 nike

<?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"]]

最佳答案

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

)

关于php - 如何使用数组实现函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com