2017-01-06 6 views
-2

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) 반환 문() 함수 :

+0

에 오신 것을 환영해야한다. [도움말]을 방문하여 [ask]를 읽으십시오. "제 코드를 수정하십시오"와 같은 질문은 작동하지 않는 것에 대한 설명을 거의하지 않고 일반적으로 수행 한 작업은 downvoted되어 오프 토픽으로 보류됩니다. –

답변

0

난 당신이 작성한 코드에 두 가지 문제가 있습니다 참조하십시오. print_r()은 부울을 반환하므로 var_dump()은 필요한 배열을 출력하지 않습니다.

return print_r($ownerFiles); 

return $ownerFiles; 

2) 하나는 지적과 질문에 언급해야한다. 대신 값을 업데이트하는 $ownerFiles[$ownerName] 배열에 $file 변수를 삽입 : -

$ownerFiles[$ownerName] = $file;  

에 유래에

$ownerFiles[$ownerName][] = $file;  
+0

Im은 xD를 반환한다는 것을 알고 있었지만 테스트를 위해서였습니다.하지만 고맙습니다 ... array_push()도 찾았지만 올바른 항목을 얻지는 못했습니다. – c0ldtrain

+0

위대한 작품, 도움을 주셔서 감사합니다, 놀랍게도 연관 배열의 항목 유형에 대한 모든 참조를 찾을 수 없습니다. – c0ldtrain