在PHP中合并2个Json文件

时间:2017-08-11 09:53:03

标签: php json merge array-merge

我想合并一些json文件,并在使用foreach函数后显示它们。

$urls = array( 'url_1','url_2', 'url_3', 'url_4', 'url_5');
$jobs = [];
foreach ($urls as $url){
$json = json_decode(get_content($url), true);
$jobs[] = $json;
}
$retour = json_encode($jobs);
foreach($retour as $job) {
 echo $job;
}

但我的屏幕上没有任何内容。我也没有错误。

当我echo $retour;时,[[{...},{...},{...},{...},{...},{...}]]代替[{...},{...},{...},{...},{...},{...}]

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我尝试了以下内容,它似乎可以按照您的意愿使用

<?php
 $urls = array( 'url_1','url_2');
 $jobs = [];
 foreach ($urls as $url){
   $json = json_decode(file_get_contents($url), true);
   array_push($jobs, $json);
 }

 $unique = array();
 foreach ($jobs as $piece) {
    $unique = array_merge($unique, $piece);
 }
 $retour = json_encode($unique);
 print_r($retour); //it gives merged json :: {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
 $test[] = $retour;
 print_r($test); //to get it as array :: ([0] => {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"})
?>

我已将url_1和url_2创建为json文件,如下所示

{
  "key1": "value1", 
  "key2": "value2"
}

{
  "key3": "value3",
  "key4": "value4"
}