PHP Группировка ключей ассоциативного массива по значениям - PullRequest
1 голос
/ 31 марта 2020
function groupByOwners(array $files) : array { return []; }

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

Print_r(groupByOwners($files);

Мой ожидаемый результат:

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

1 Ответ

2 голосов
/ 31 марта 2020

Вам просто нужно перебрать свой массив, переместив каждое имя файла в новый массив, индексированный именами:

function groupByOwners(array $files) : array { 
    $output = array();
    foreach ($files as $file => $name) {
        $output[$name][] = $file;
    }
    return $output;
}

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

print_r(groupByOwners($files));

Вывод:

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

Демонстрация на 3v4l .org

...