Reputation: 2113
I have this SQL statement in my list_user_ads() function that will find an adverts and images for a specific user
$row = $this->db->dbh->prepare('SELECT ad.*, (SELECT GROUP_CONCAT(img.image) FROM '.$this->config->db_prefix.'_images AS img WHERE img.aid = ad.aid) AS img FROM '.$this->config->db_prefix.'_adverts ad WHERE fid = :fid ORDER BY cr_date DESC');
and this
$res = $adverts->list_user_ads($id->fid);
json_encode($res);
will give me a json that looks like this:
[
{
"aid": "80",
"fid": "703640495",
"title": "gxj",
"text": "Hbccgg",
"price": "800.00",
"category": "10",
"friends_allow": "1",
"cr_date": "1380010359",
"expiry_date": "1385197959",
"approved": "1",
"ip": "80.164.52.106",
"name": "Morten Peter Hagh Jensen",
"email": "[email protected]",
"publish_email": "1",
"zip_for_pickup": "9000",
"views": "4",
"num_reports": "0",
"img": "703640495-1380010326490.jpg,703640495-rt804-villa-a_9.jpg"
},
{
"aid": "76",
"fid": "703640495",
"title": "Hfjg",
"text": "Chef",
"price": "4645.00",
"category": "1",
"friends_allow": "1",
"cr_date": "1380009351",
"expiry_date": "1385196951",
"approved": "1",
"ip": "80.164.52.106",
"name": "Morten Peter Hagh Jensen",
"email": "[email protected]",
"publish_email": "1",
"zip_for_pickup": "9000",
"views": "2",
"num_reports": "0",
"img": "703640495-image_20.jpg"
}
]
The images are commaseparated, but I have to explode that key so I will get a result that will look like this:
[
{
"aid": "80",
"fid": "703640495",
"title": "gxj",
"text": "Hbccgg",
"price": "800.00",
"category": "10",
"friends_allow": "1",
"cr_date": "1380010359",
"expiry_date": "1385197959",
"approved": "1",
"ip": "80.164.52.106",
"name": "Morten Peter Hagh Jensen",
"email": "[email protected]",
"publish_email": "1",
"zip_for_pickup": "9000",
"views": "4",
"num_reports": "0",
"img": [{
"703640495-1380010326490.jpg",
"703640495-rt804-villa-a_9.jpg"
}]
},
{
"aid": "76",
"fid": "703640495",
"title": "Hfjg",
"text": "Chef",
"price": "4645.00",
"category": "1",
"friends_allow": "1",
"cr_date": "1380009351",
"expiry_date": "1385196951",
"approved": "1",
"ip": "80.164.52.106",
"name": "Morten Peter Hagh Jensen",
"email": "[email protected]",
"publish_email": "1",
"zip_for_pickup": "9000",
"views": "2",
"num_reports": "0",
"img": [{"703640495-image_20.jpg"}]
}]
But I can't seem to figure out how to do it.
I have tried with a foreach and explode $value["img"] and put it into an array and then join that array with the $res array, but that put the images separately at the bottom of the json object.
POSSIBLE SOLUTION:
foreach($res as $key => $value) {
$images[] = array("images" => explode(",", $value["img"]));
}
$new = array_replace_recursive($res, $images);
Upvotes: 0
Views: 393
Reputation: 677
You may use an array_map on your $res to process each item before json_encode it.
Something like
$return = array_map(
function($item) { $item['img'] = explode(',', $item['img']; return $item; },
$res
);
json_encode($res);
Upvotes: 1