我有来自两个 mysql 表的 2 个 JSON 数组,即 db_events
和 db_ads
。
在 db_events
的 JSON 值中,我想分别在位置 5 处添加来自 db_ads
的第一个 JSON 值,在位置 10 处添加第二个值。
我该如何实现这个。这可能吗?
来自表 db_events
的 JSON 是,
{
"events_from_category": [
{
"id": "1",
"name": "Demo Event"
},
{
"id": "2",
"name": "Demo"
},
{
"id": "3",
"name": "Event"
},
{
"id": "4",
"name": "fgvnjhfrjht"
},
{
"id": "5",
"name": "fgvnjhfrjht"
},
{
"id": "6",
"name": "fgvnjhfrjht"
},
{
"id": "7",
"name": "fgvnjhfrjht"
},
{
"id": "8",
"name": "fgvnjhfrjht"
},
{
"id": "9",
"name": "fgvnjhfrjht"
},
{
"id": "10",
"name": "fgvnjhfrjht"
}
]
}
来自表 db_ads
的 JSON 是,
{
"ads": [
{
"id": "1",
"ads_name": "ads 1"
},
{
"id": "2",
"ads_name": "ads 2"
}
]
}
我生成的 JSON 应该是,
{
"ads": [
{
"id": "1",
"name": "Demo Event"
},
{
"id": "2",
"name": "Demo"
},
{
"id": "3",
"name": "Event"
},
{
"id": "4",
"name": "fgvnjhfrjht"
},
{
"id": "1",
"ads_name": "ads 1"
},
{
"id": "6",
"name": "fgvnjhfrjht"
},
{
"id": "7",
"name": "fgvnjhfrjht"
},
{
"id": "8",
"name": "fgvnjhfrjht"
},
{
"id": "9",
"name": "fgvnjhfrjht"
},
{
"id": "2",
"ads_name": "ads 2"
}
]
}
最佳答案
首先要注意的是 json 可以使用以下方式解码为数组:
$aryRecords = json_decode($strRecords);
$aryAds = json_decode($strAds);
然后,因为您不只是追加,所以有必要开始循环数组以在某些点插入广告:
$aryTemp = array();
$intCount = 0;
/* Make sure pointer at the start of the ads array */
reset($aryAds);
/* Start looping through your results */
foreach($aryRecords as $aryCurrentRecord) {
$intCount++;
/* Check if counter divisible by 5 */
if($intCount %5 != 0) {
$aryTemp[] = current($aryAds);
/* Move the pointer in the ads array forward */
next($aryAds);
}
$aryTemp[] = $aryCurrentRecord;
}
/* Recreate your JSON object */
$strOutput = json_encode($aryTemp);
关于php - 使用 PHP 在指定位置合并 2 个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068029/