[英]php merge json arrays into one array
我試圖遍歷一些 json 文件,並將它們組合成一個 json 文件。 我的計划是擁有一個全局$allData
數組,並將新的候選者合並到其中。
<?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"}
組合.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"}]]
你的合並很奇怪:
$result = array_merge($allData,$data);
您想將每個新的$data
數組合並到一個不斷增長的$allData
數組中,對嗎? 我認為你想這樣做:
$allData = array_merge($allData,$data);
你也可以擺脫這個,這是沒有必要的。
if($count == 0){
$allData = $data;
}
如前所述, $result = array_merge($allData,$data);
是合並數組的最佳方式。 這段代碼可以合並兩者,但是,問題是我的 json 格式不正確。
我的兩個文件周圍沒有[]
,因此無法正確合並它們。
我的解決方案很糟糕,但它有效:我用逗號替換字符串一的 },刪除第二個字符串的 { 並連接這兩個字符串......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.