简体   繁体   English

在PHP中合并2个Json文件

[英]Merge 2 Json file in PHP

i want to merge some json file and display them after using a foreach function. 我想合并一些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;
}

But nothing appear on my screen. 但是我的屏幕上什么也没有出现。 And i have no error too. 而且我也没有错误。

When i do echo $retour; 当我echo $retour; i have something like [[{...},{...},{...},{...},{...},{...}]] instead of [{...},{...},{...},{...},{...},{...}] . 我有类似[[{...},{...},{...},{...},{...},{...}]]而不是[{...},{...},{...},{...},{...},{...}]

How to solve this ? 如何解决呢?

I have tried the following and it seems to work as you want 我尝试了以下方法,它似乎可以按照您的要求工作

<?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"})
?>

I have created url_1 and url_2 as json file as follow 我已经将url_1和url_2创建为json文件,如下所示

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM