[英]How to get json format in php
[{"section_name": "Section A","data": [{"value": "2"},{"value": "0"}]}, {"section_name": "Section B","data": [{"value": "1"},{"value": "0"}]}] [{“ section_name”:“ A节”,“数据”:[{“ value”:“ 2”},{“ value”:“ 0”}]},{“ section_name”:“ B节”,“数据“:[{” value“:” 1“},{” value“:” 0“}]}]
In this I am retrieving "section_name","value"
from database. 在此,我正在从数据库中检索"section_name","value"
。
Here the concept is get values from database to display a bar chart, based on classes and sections. 这里的概念是根据类和节从数据库获取值以显示条形图。
But my template I had chosen, I have to get the values(no. of students in a class & section) for individual sections, as shown in below bar chart. 但是我选择的模板,我必须获取各个部分的值(班级和部分的学生人数),如下面的条形图所示。
My PHP Code: 我的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);
} }
My JSON CODE: 我的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
}
]
}
]
I am using this json in ajax Hope you guys understand question. 我在ajax中使用此json希望大家理解问题。 http://i.stack.imgur.com/mlfLJ.jpg http://i.stack.imgur.com/mlfLJ.jpg
You can't act in your way. 你不能以自己的方式行事。 To produce a valid JSON string, you can write this code: 要生成有效的JSON字符串,您可以编写以下代码:
$data = array( array('category'=>$data1), array('section'=>$data2), array('category'=>$data3) );
$json = json_encode( $data );
Or — if you have more $dataN
arrays — by this way: 或者-如果您有更多$dataN
数组-通过这种方式:
$data = array();
// Your first MySQL query here
$data[] = array( 'category' => $rows1 );
// Your second MySQL query here
$data[] = array( 'section' => $rows2 );
// (...)
$json = json_encode( $data );
mysql_ syntax was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. mysql_语法在PHP 5.5.0中已弃用,在PHP 7.0.0中已删除 。 Instead, the MySQLi or PDO_MySQL extension should be used. 相反,应使用MySQLi或PDO_MySQL扩展。
(from PHP Official site) (来自PHP官方站点)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.