我是 PHP 新手,我想生成这样的 json 代码
[{"section_name": "Section A","data": [{"value": "2"},{"value": "0"}]}, {"section_name": "Section B","data": [{"value": "1"},{"value": "0"}]}]
在此我正在从数据库中"section_name"
检索。"value"
这里的概念是从数据库中获取值以显示基于类和部分的条形图。
但是我选择的模板,我必须获取各个部分的值(班级和部分中的学生人数),如下面的条形图所示。
我的 PHP 代码:
$result1 = mysql_query("select class_name as label from class ") or die(mysql_error());
while($row1 = mysql_fetch_assoc($result1))
{
$rows1[] = $row1;
}
$data1 = json_encode($rows1);
$result2 = mysql_query("select s.section_name as sectionname, 'data' as data from section s") or die(mysql_error());
$result3 = mysql_query("select (select count(*)as c from student_status ss where ss.section_id=s.section_id and ss.class_id=c.class_id) as value from section s, class c order by s.section_name asc ") or die(mysql_error());
if(mysql_num_rows($result2) > 1)
{
while($row2 = mysql_fetch_assoc($result2))
{
$rows2[] = $row2;
}
$data2 = json_encode($rows2);
while($row3 = mysql_fetch_assoc($result3))
{
$rows3[] = $row3;
}
$data3 = json_encode($rows3);
}
我的 JSON 代码:
"categories": [
{
"category": <? echo $data1 ?>/*[
{
"label": "1"
},
{
"label": "TWO"
},
{
"label": "3"
}
]*/
}
],
"dataset": /*<? echo $data2 ?>*/[
{
"sectionname": "Section A",
"data": [
{
"value": "2" //class 1
},
{
"value": "1" //class 2
}
]
},
{
"sectionname": "Section B",
"data": [
{
"value": "" //class 1
},
{
"value": "" //class2
}
]
}
]
希望大家理解问题。