PHP의 랩 손연관 배열을 다음 iterating var와 병합하는 방법?</p> <p>각 파일명의 파일 소유자의 이름을 포함하는 결합 배열을 받아 들인다 :
에서 groupByOwners하면 해당 기능 구현. 각 소유자 이름에 대한 파일 이름 배열을 임의의 순서로 포함하는 연관 배열을 반환합니다.
예를 들어, 연관 배열 ["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"] the groupByOwners function should return ["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]
의 경우.
저는 꽤 많이 했어요. 두 번째 파일 소유자의 행을 확장하는 방법을 알아내는 것과 함께 array_merge()를 사용하여 문제가 발생했습니다.
여기 내 코드입니다 :
<?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));
그리고 문제 영역 바로 여기에있다. 위 읽으면
foreach ($files as $file => $currentOwner) {
// if file is matching the current owner and,
if ($ownerName == $currentOwner) {
echo $file.$ownerName;
$ownerFiles[$ownerName] = $file;
}
}
, 문제는 내가, 내가 내 출력을 원하는 것이다 그러나 그것은 단지 배열을 지원하는 문자열로 연관 배열을 병합 array_merge()를 사용하는 것을 시도하고 있다는 것입니다 같은 :
[ "Randy"=> [ "Input.txt", "Output.txt"] "Stan"=> [ "Code.py"]]`
내 주문에 대한 실험실 작업은 중요하지 않습니다. 교육적 이익. groupByOwners의
1) 반환 문() 함수 :
에 오신 것을 환영해야한다. [도움말]을 방문하여 [ask]를 읽으십시오. "제 코드를 수정하십시오"와 같은 질문은 작동하지 않는 것에 대한 설명을 거의하지 않고 일반적으로 수행 한 작업은 downvoted되어 오프 토픽으로 보류됩니다. –