The PHP lab at hand
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 function should return ["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]
.
I'm pretty much done, I just had issues using array_merge(), along with figuring out how to extend the row for the second file owner.
Here's my code:
<?php
class FileOwners {
public static function groupByOwners($files) {
$i = 0;
$totalOwners=0;
$lastOwners[0] = 0;
$ownerFiles = array();
//input associative array.
foreach ($files as $file => $currentOwner) {
//echo $currentOwner.':'.$file;
// if the last owner checked matches the current, do not backup the owner name.
if ($currentOwner == $lastOwners[$i]) {
//subtract count of how many owners are found by 1.
$totalOwners=$totalOwners-1;
} else {
//Backup the the new owner found.
$namesOfOwners[$i]=$currentOwner;
};
$i++;
$totalOwners++;//count total owners.
$lastOwners[$i] = $currentOwner;
}
$i=0;
$fileCount=0;
// for all owners found (2) test case
foreach ($namesOfOwners as $ownerName) {
//match there own files to there respective arrays, in the order of 0-?
foreach ($files as $file => $currentOwner) {
// if file is matching the current owner and,
if ($ownerName == $currentOwner) {
echo $file.$ownerName;
$ownerFiles[$ownerName] = $file;
}
}
$i++;
}
return print_r($ownerFiles);
}
}
$files = array(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy",
);
var_dump(FileOwners::groupByOwners($files));
And the problem area is right here.
foreach ($files as $file => $currentOwner) {
// if file is matching the current owner and,
if ($ownerName == $currentOwner) {
echo $file.$ownerName;
$ownerFiles[$ownerName] = $file;
}
}
if you read above, the issue is that I'm trying to use array_merge() to merge an associative array with a string however it only supports arrays, i would want my output as:
["Randy" => ["Input.txt", "Output.txt"] "Stan" => ["Code.py"]]`
neither order matters, im just doing the lab for my own educational benefit.
I see there are two issues with the code you've written:
1) Return statement of groupByOwners() Function. print_r()
will return boolean, hence the var_dump()
will never output the array you need.
return print_r($ownerFiles);
should be
return $ownerFiles;
2) The one you pointed and mentioned in the question. Instead of updating the values, insert the $file
variable into $ownerFiles[$ownerName]
array:-
$ownerFiles[$ownerName] = $file;
should be
$ownerFiles[$ownerName][] = $file;