首页 > 解决方案 > PHP 将 2 个 Json 合并为 1 个

问题描述

我有 2 个要解析的 JSON 文件,并合并到一个对象中并作为单个 JSON 输出。但我不知道该怎么做并得到正确的结果,每次我尝试总是得到一个这样的结果:

[
    {
        "Title": "Some title for your blog",
        "url": "\/post.php?id=1",
        "image": "https:\/\/example.com\/images\/small\/1.jpg"
    }
]

我需要将所有 2 个 json 数据调用为 1 个 json,如下所示:

[
    {
        "Title": "second title for your blog",
        "url": "\/post.php?id=2",
        "image": "https:\/\/example.com\/images\/small\/2.jpg"
    }

    {
        "Title": "second title for your blog",
        "url": "\/post.php?id=2",
        "image": "https:\/\/example.com\/images\/small\/2.jpg"
    }
    {
        "Title": "third title for your blog",
        "url": "\/post.php?id=3",
        "image": "https:\/\/example.com\/images\/small\/3.jpg"
    }

    and so on... till the end of loop
]

这是我的代码:

$requestUrl="http://example.com/json1.php";
$requestUrl1="http://example.com/json2.php";

$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);

$array1 = json_decode($data);
$array2 = json_decode($data1);


$wholedata= [];
$i=0;
foreach ($array1 as $array1) {
    $item['Title'] = $array1->title;
    $item['url'] = $array1->url;
}   
foreach ($array2 as $array2) {
    $item['image'] = $array2->image;
}

$wholedata[] = $item;
            $i++;

$json = json_encode($wholedata, JSON_PRETTY_PRINT);

header('Access-Control-Allow-Origin: *');
header('Content-type: Application/JSON');

echo $json;

这是json数据:

json 1

[
    {
        "title": "first title for your blog",
        "url": "/post.php?id=1"
    },
    {
        "title": "Second title for your blog",
        "url": "/post.php?id=2"
    },
    {
        "title": "Third title for your blog",
        "url": "/post.php?id=3"
    },
    {
        "title": "Fourth title for your blog",
        "url": "/post.php?id=4"
    },
    {
        "title": "Fifth title for your blog",
        "url": "/post.php?id=5"
    }
]

json 2:

[
    {
        "image": "https://example.com/images/small/1.jpg"
    },
    {
        "image": "https://example.com/images/small/2.jpg"
    },
    {
        "image": "https://example.com/images/small/3.jpg"
    },
    {
        "image": "https://example.com/images/small/4.jpg"
    },
    {
        "image": "https://example.com/images/small/5.jpg"
    }
]

标签: phparraysjson

解决方案


要对对象执行此操作(如您当前使用的那样),您可以使用第一个数组的索引从第二个数组中获取数据。然后使用来自两个对象的组件一次性构建输出并将它们添加到您的输出中......

$array1 = json_decode($data);
$array2 = json_decode($data1);

$wholedata= [];
foreach ($array1 as $key => $itemData) {
    $wholedata[] = ['Title' => $itemData->title,
        'url' => $itemData->url,
        'image' => $array2[$key]->image];
}

$json = json_encode($wholedata, JSON_PRETTY_PRINT);

推荐阅读