[英]Merge 2 Json file in PHP
我想合並一些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;
我有類似[[{...},{...},{...},{...},{...},{...}]]
而不是[{...},{...},{...},{...},{...},{...}]
。
如何解決呢?
我嘗試了以下方法,它似乎可以按照您的要求工作
<?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"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.