I have 2 JSON array from two mysql tables ie, db_events
and db_ads
.
Inside JSON values from db_events
, I want to add first JSON value from db_ads
at position 5 and second value at position 10 respectively.
How can I implement this. Is this is possible.
JSON from table db_events
is,
{
"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"
}
]
}
JSON from table db_ads
is,
{
"ads": [
{
"id": "1",
"ads_name": "ads 1"
},
{
"id": "2",
"ads_name": "ads 2"
}
]
}
My resulting JSON should be,
{
"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"
}
]
}
The first thing to note is that json can be decoded in to an array using:
$aryRecords = json_decode($strRecords);
$aryAds = json_decode($strAds);
Then, because you are not just appending, it will be necessary to start looping through the array to insert the ads at certain points:
$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);