我有这个查询,我已经运行以从三个表中收集数据。我想从收集的这些数据中创建JSON。我编写了以下脚本来创建它。如果有任何快速或聪明的解决方法,请指导我。
这是我需要从以下位置创建JSON的数据库结果的快照:
我正在使用的脚本就是这个。
$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);
这给了我粘贴在下面的结果。
[[[{"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"}]]]]
但我正在寻找下面的结果。
{
"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.....",
}
]
}
]
}
任何帮助或指导都会非常有帮助。
答案 0 :(得分:1)
试试这个,它会给你你期望的结果:
$typeArr = array();
foreach($result as $a){
$typeArr[$a['chanct_name']][] = array(
'name'=>$a['con_name'],
'image'=>$a['con_image']
);
}
$jsonarray = array();
foreach($typeArr as $type=>$contents){
$jsonarray['channelsCategories'][] = array(
'name'=>$type,
'contents'=>$contents
);
}
echo json_encode($jsonarray);