Create JSON in PHP using database -
i have query have run gather data 3 tables. want create json data gathered. have written following script create it. please guide me if there quick or smart workaround this.
this snapshot of database result need create json from:
script i'm using this.
$jsonarray = array(); while ($i<count($result)) { $channel_cat = array("channel category" => array("name" => $result[$i]['chanct_name'])); $id = $result[$i]['chanct_id']; while($id == $result[$i]['chanct_id']) { $content[] = array( "channel name" => $result[$i]['con_name'], "image" => $result[$i]['con_image']); $i++; } $jsonarray[][] = array($channel_cat, $content); unset($content); } echo json_encode($jsonarray);
this gives me result pasted below.
[[[{"channel category":{"name":"movie"}}, [{"channel name":"channel1","image":"thanks.jpg"}, {"channel name":"channel2","image":"thanks.jpg"}, {"channel name":"channel4","image":"amazon-logo-b_tpng.png"}, {"channel name":"high","image":"thanks.jpg"}]]] ,[[{"channel category":{"name":"documentary"}}, [{"channel name":"channel7","image":"amazon-logo-b_tpng.png"}]]]]
however looking result below.
{ "channelscategories": [ { "name":"movie", "image": "movieposter", "contents": [ { "name":"channel 1", "image":"thanks.jpg", }, { "name":"channel 2", "image":"thanks.jpg", }, { "name":"channel 4", "image":"amazon-logo...", }, { "name":"high", "image":"thanks.jpg", } ] }, { "name":"documentary", "image": "movieposter", "contents": [ { "name":"channel 7", "image":"amazon.....", } ] } ] }
any or guidance helpful.
try this, give result expecting:
$typearr = array(); foreach($result $a){ $typearr[$a['chanct_name']][] = array( 'name'=>$a['con_name'], 'image'=>$a['con_image'] ); } $jsonarray = array(); foreach($typearr $type=>$contents){ $jsonarray['channelscategories'][] = array( 'name'=>$type, 'contents'=>$contents ); } echo json_encode($jsonarray);
Comments
Post a Comment