我有一些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 循环中它以 }, {
结尾,但我需要它以 }]
结尾
我该如何解决这个问题 - 随着用户能够添加/删除类别,工单表中的类别项目数量一直在变化。
为什么不这样做:
<?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);
<?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 '}]';
?>
将括号放在书签中,尽管最好构建它然后回显它,这样您就可以摆脱最后一个逗号。
$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]";
试试
$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) . ']';
但正如 Rich 所说,你真的不应该手写 JSON。