Razer
Razer

Reputation: 11

PHP Group keys of associative array by values

function groupByOwners(array $files) : array { return []; }

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

Print_r(groupByOwners($files);

My expected output is:

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

Upvotes: 1

Views: 199

Answers (1)

Nick
Nick

Reputation: 147216

You just need to iterate over your array, pushing each filename to a new array indexed by the names:

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

Output:

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

Demo on 3v4l.org

Upvotes: 2

Related Questions