Click here to Skip to main content
14,735,287 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
<?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));


Implement a groupByOwners function that:
1.Accepts an associative array containing the file owner name for each file name.
2.Returns an associative array containing an array of file names for each owner name, in any order.

What I have tried:

Quote:
For example that I thought, 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"]].
Posted
Updated 10-Apr-20 5:05am
v2

You will need an associative array where each key is associated with an array of files, to achieve this, try this:
public static function groupByOwners($files)
{
	foreach($files as $file => $name) {
		
		if (isset($newArray[$name])) {
            // if key exists, add to its array of elements
			array_push($newArray[$name], $file);
		} else {
            // else create a new array element
			$newArray[$name] = array($file);
		}
	}

	return $newArray;
}
   
class FileOwners
{
 public static function groupByOwners($files)
    {
        $result=array();
        foreach($files as $key=>$value)
        {
            $result[$value][]=$key;
        }
        return $result;
    }
}
   
v2
public static function groupByOwners($files) {

$file_return = [];
//print_r($files);

foreach ($files as $x => $x_value) {
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);

foreach ($file_return as $key => $value) {
if (isset($value[1])) {
$output = "['" . $key . "' => ['" . $value[0] . "','" . $value[1] . "'],";
//echo"['" . $key . "' => ['" . $value[0] . "','" . $value[1] . "'],";
} else {
$output = $output. " '" . $key . "' => ['" . $value[0] . "']]";
//echo " '" . $key . "' => ['" . $value[0] . "']]";
}
}
return $output;
}
   
<?php

function groupByOwners(array $files) : array
{
    $list = [];
    foreach ($files as $key => $value) {
    	$list[$key][] = $value; 
    }
    return $list;
}

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900