Skip to content

Instantly share code, notes, and snippets.

@mllopart
Created June 14, 2017 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mllopart/648195c19813d4682e185ee8a69af451 to your computer and use it in GitHub Desktop.
Save mllopart/648195c19813d4682e185ee8a69af451 to your computer and use it in GitHub Desktop.
Implement a groupByOwners function that: Accepts an associative array containing the file owner name for each file name. Returns an associative array containing an array of file names for each owner name, in any order. For example, for associative array ["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"] the groupByOwners func…
<?php
class FileOwners
{
public static function groupByOwners($files)
{
$file_return = [];
$files_copy = $files;
print_r($files);
foreach($files as $x => $x_value) {
$found = false;
if (array_key_exists($x_value,$file_return))
array_push($file_return[$x_value], $x);
else {
$file_return[$x_value] = array();
array_push($file_return[$x_value], $x);
}
}
print_r($file_return);
return NULL;
}
}
$files = array
(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
);
var_dump(FileOwners::groupByOwners($files));
@rkbwp
Copy link

rkbwp commented Aug 17, 2020

function groupByOwners(array $files) : array
{
    $result = [];

    foreach($files as $file => $owner) {
        $result[$owner][] = $file;
    }

    return $result;
}

@VoDangVinh2000
Copy link

thanks rkbwp

@kirilinko
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment