2013-12-08 3 views
4

일부 json 파일을 반복하여 하나의 json 파일로 결합하려고합니다. 내 계획은 세계 $allData 배열을 가지고 있으며, 새 후보를 병합하기 만하면됩니다.php json 배열을 하나의 배열로 병합

<?php 
$allData = array(); 
$count = 0; 
if ($handle = opendir('./json/')) { 
    while (false !== ($entry = readdir($handle))) { 
     if ($entry != "." && $entry != "..") { 

      echo $entry."<br />"; 

      $source_file = file_get_contents('./json/'.$entry); 

      $data = json_decode($source_file,TRUE); 

      if($data != null){ 


       $allData = array_merge($allData,$data); 
       echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />"; 
       print_r($allData); 

      } 
      else{ 
       echo "Invalid Json File"; 
      } //end else    
     } 
closedir($handle); 
} 

echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />"; 

print_r($allData); 

그러나 병합으로 파일을 덮어 씁니다. 여러 개의 json 파일을 어떻게 하나로 결합 할 수 있습니까?

1.json :

{"date":"10"},{"comment":"some comment"},{"user":"john"} 

2.json :

{"date":"11"},{"comment":"another quote"},{"comment":"jim"} 

combined.json

[{"date":"10"},{"comment":"some comment"},{"user":"john"}, 
{"date":"11"},{"comment":"another quote"},{"comment":"jim"}] 

난 단지입니다

나는 다음과 같은 결과를 싶습니다 이 값들 중 하나를 얻는다. 배열을 병합합니다.

[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}, 
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]] 
+0

json_decode() 데이터와 함께 array_merge()를 사용해 보셨습니까? – PKeidel

답변

8

병합은 홀수 :

$result = array_merge($allData,$data); 

당신은 바로 성장 $allData 배열에 각각의 새로운 $data 배열을 병합되고 싶어? 대신 다음과 같이하고 싶다고 생각합니다.

$allData = array_merge($allData,$data); 

또한 제거 할 필요가 없습니다.

if($count == 0){ 
    $allData = $data; 
} 
+0

논리가 있으므로 덮어 쓰지 않습니다. 그리고 $ allData는 이미 위에 선언되었습니다. – nook

+0

@ publ1c_stat1c 업데이트 된 답변보기 '$ result'는 일을 복잡하게 만들고 있다고 생각합니다. '$ data'를'$ allData'로 합치고 매번 새로운'$ allData'로 설정하십시오. – jszobody

+0

나는 이것을 추구했고, 나는 여전히 원하는 결과를 얻지 못했다. 여전히 덮어 씌워지고 있습니다. – nook

2

앞에서 설명한 것처럼 $result = array_merge($allData,$data);은 배열을 병합하는 가장 좋은 방법입니다. 이 코드는 두 개를 병합하기 위해 작동하지만 문제는 내 json이 제대로 구성되지 않았다는 것입니다.

내 두 파일 주위에 []이 없으므로 제대로 병합 할 수 없습니다.

관련 문제