我有一些用于显示图形数据的JS代码:
series: [{
name: 'Year 1800',
data: [107, 31, 635, 203, 2]
}, {
name: 'Year 1900',
data: [133, 156, 947, 408, 6]
}, {
name: 'Year 2008',
data: [973, 914, 4054, 732, 34]
}]
我需要在PHP中使用while循环显示数据。我试过这个:
<?php
$sql="SELECT *, COUNT(category) AS my_groupcount from tickets where deleted = '' and DAY(datetime) = '".$day."' and MONTH(datetime) = '".$month."' and YEAR(datetime) = '".$year."' group by category order by datetime ASC ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs))
{
echo "name: 'Cat ".$result["category"]."',";
echo "data: [".$result["my_groupcount"]."]";
echo "}, {";
}
?>
我需要对故障单表中的类别列进行分组并显示每个类别的图表但它不起作用 - 我认为这是因为在while循环中它以}, {
结尾但我需要以{结尾{ {1}}
我该如何解决这个问题 - 由于用户可以添加/删除类别,故障单表格中的类别项目数量会一直在变化。
答案 0 :(得分:4)
为什么不这样做:
<?php
$sql = "[.. SQL Statement ..]";
$rs = mysql_query($sql, $conn);
$json = array();
while($result = mysql_fetch_array($rs)) {
$json[] = array(
'name' => 'Cat '. $result['category'],
// This does assume that my_groupcount is an array with numbers
// i.e. array(1, 34, 54, 345)
// If not, you'll have to make it an array by doing:
// explode(', ', $result['my_groupcount'])
// This however does assume that the numbers are in
// the "12, 23" format
'data' => $result['my_groupcount'],
);
}
echo json_encode($json);
答案 1 :(得分:1)
<?php
$sql="SELECT *, COUNT(category) AS my_groupcount from tickets where deleted = '' and DAY(datetime) = '".$day."' and MONTH(datetime) = '".$month."' and YEAR(datetime) = '".$year."' group by category order by datetime ASC ";
$rs=mysql_query($sql,$conn);
$first = true;
echo 'series: [{';
while($result=mysql_fetch_array($rs))
{
if(!$first) {
echo "}, {";
} else {
$first = false;
}
echo "name: 'Cat ".$result["category"]."',";
echo "data: [".$result["my_groupcount"]."]";
}
echo '}]';
?>
答案 2 :(得分:0)
支持括号,虽然最好构建它然后回显它,这样你就可以摆脱最后一个逗号。
$string = '';
while($result=mysql_fetch_array($rs))
{
string.= "{";
string.= "name: 'Cat ".$result["category"]."',";
string.= "data: [".$result["my_groupcount"]."]";
string.= "},";
}
$string = trim($string,','); // gets rid of that last comma
echo "[$string]";
答案 3 :(得分:0)
试
$sql="SELECT *, COUNT(category) AS my_groupcount from tickets where deleted = '' and DAY(datetime) = '".$day."' and MONTH(datetime) = '".$month."' and YEAR(datetime) = '".$year."' group by category order by datetime ASC ";
$rs=mysql_query($sql,$conn);
$output = '[';
while($result=mysql_fetch_array($rs))
{
$output .= "name: 'Cat ".$result["category"]."',";
$output .= "data: [".$result["my_groupcount"]."]";
$output .= "}, {";
}
$output = substr($output, 0, -3) . ']';
但富裕说你真的不应该手工编写JSON。