我有两个mysql表中的2个JSON数组,即db_events
和db_ads
。
来自db_events
的JSON值内部,我想分别从位置5的db_ads
和位置10的第二个值添加第一个JSON值。
我该如何实现呢?这是可能的。
表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"
}
]
}
答案 0 :(得分:1)
首先要注意的是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);