【发布时间】:2016-02-23 23:15:54
【问题描述】:
[{"section_name": "Section A","data": [{"value": "2"},{"value": "0"}]}, {"section_name": "Section B" ,"数据": [{"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
}
]
}
]
我在 ajax 中使用这个 json 希望大家理解问题。 http://i.stack.imgur.com/mlfLJ.jpg
【问题讨论】:
-
你需要stop using mysql_ functions,因为它们在 PHP 7 中被删除了
-
这简直太恶心了。您应该 不 像这样将 php 值嵌入到 json 中。您很可能会引入导致 json 解析错误的无效文本。换句话说,NEVER 手动构建 json,当您可以构建原生 php 数组数据结构时,然后对该数组执行单个
json_encode()调用。砰,完成。 -
至于“访问”json - 你没有。 json 是一种传输/编码格式。它实际上只是一个纯文本字符串。您将 json 解码为本机数据结构,并通过该结构访问您的数据。
-
你好Marc B,看来你的话很有用,我听不懂你在说什么,简单告诉我,问候。