我正在尝试遍历一些 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;
}
关于php将json数组合并为一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20460039/