我有多个 JSON 文件,我想对其进行解析、编辑和合并到一个对象中,最终将其重新编码并输出为单个 JSON。
我目前有一个关于何时解析和编辑一个对象的工作示例,但我不知道如何做两个并获得一个结果。
工作示例:
$source = 'http://www.jakedup.com/_/source1';
$data = json_decode(file_get_contents($source));
// THIS WILL BE THE FINAL OUTPUT OBJECT
$output = new stdClass();
// GET THE ARTICLE DATES AS AN ARRAY
$tracks = get_object_vars($data->tracks);
// LOOPS OVER ARTICLE PUBDATES TO GET THE OUTER OBJECTS
foreach ($tracks as $key=>$val) {
// LOOPS OVER THE INNER OBJECTS IN EACH ARTICLE PUBDATE
foreach ($data->tracks->$key as $object) {
// ADD IT ONTO THE OUTPUT OBJECT WITH "ID" AS PARENT NAME
$output->{$object->id} = $object;
}
}
echo json_encode($output);
这是我的 JSON 示例。我提供了两个示例,但我正在寻找一种动态合并无限数量的 JSON 文件的方法。
JSON 源 1:
{
"foo":"bar",
"tracks":{
"1349496000":[
{
"id":"25328",
"is_promo":null,
"is_feature":null,
"listens":"1312",
"downloads":"777"
},
{
"id":"25327",
"is_promo":null,
"is_feature":null,
"listens":"1255",
"downloads":"578"
},
{
"id":"25329",
"is_promo":null,
"is_feature":null,
"listens":"341",
"downloads":"139"
}
],
"1349323200":[
{
"id":"25310",
"is_promo":null,
"is_feature":null,
"listens":"10793",
"downloads":"4953"
}
]
}
}
JSON 源 2:
{
"foo":"bar",
"tracks":{
"1349323200":[
{
"id":"25303",
"is_promo":null,
"is_feature":null,
"listens":"2347",
"downloads":"1499"
}
],
"1349236800":[
{
"id":"25266",
"is_promo":null,
"is_feature":null,
"listens":"24485",
"downloads":"19366"
}
]
}
}
我一直在玩弄循环获取源的想法,但是在合并数据时我被卡住了。我所有的不同努力都没有产生正确的数据结构。
当前测试代码:
$source = 'http://www.jakedup.com/_/source';
$pages = 2;
for ($i = 1; $i <= $pages; $i++) {
$sources[$i] = $source.$i;
${'source'.$i} = json_decode(file_get_contents($source.$i));
}
我现在有两个对象——$source1 和 $source2——但我不确定下一步该做什么。
这是我期待的输出:
{
"25328": {
"id": "25328",
"is_promo": null,
"is_feature": null,
"listens": "1312",
"downloads": "777",
"timestamp": "1349496000"
},
"25327": {
"id": "25327",
"is_promo": null,
"is_feature": null,
"listens": "1255",
"downloads": "578",
"timestamp": "1349496000"
},
"25329": {
"id": "25329",
"is_promo": null,
"is_feature": null,
"listens": "341",
"downloads": "139",
"timestamp": "1349496000"
},
"25310": {
"id": "25310",
"is_promo": null,
"is_feature": null,
"listens": "10793",
"downloads": "4953",
"timestamp": "1349323200"
},
"25303": {
"id": "25303",
"is_promo": null,
"is_feature": null,
"listens": "2347",
"downloads": "1499",
"timestamp": "1349323200"
},
"25266": {
"id": "25266",
"is_promo": null,
"is_feature": null,
"listens": "24485",
"downloads": "19366",
"timestamp": "1349236800"
}
}
在此先感谢您的帮助!