嗨,我已经广泛搜索了这个并在很多方面进行了调整,但我就是无法正确处理。
我的目标是从反馈表中检索 mysql 数据并绘制一个 flot.js 图表。到目前为止,我可以用这个检索数据:
$query = "SELECT flavor, COUNT(flavor) FROM $tbl_name GROUP BY flavor";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result))
{
$dataset1[] = array($rows['flavor'],$rows['COUNT(flavor)']);
}
这将检索风味评级(优秀、良好、平均或差),并计算每个在反馈中使用了多少次,数组如下所示:
[["average","1"],["bad","1"],["excellent","1"],["good","2"]]
flot.js 需要我的 x,y 值是数字,所以我在调用 $dataset 1 时设法使用 JSON_NUMERIC_CHECK 将数值更改为整数,所以现在它看起来像这样:
[["average",1],["bad",1],["excellent",1],["good",2]]
我不知道如何将单词"优秀、良好、平均和不良"转换为简单的数值,例如:"优秀"一词应该是 1,"好"应该是 2,依此类推,所以我的 flot 数据输出如下:
[[3,1],[4,1],[1,1],[2,2]]
这是我的很多 javascript:
$(function () {
$.plot(
$("#graph"),
[
{
label: "Flavor",
data: <?php echo json_encode($dataset1, JSON_NUMERIC_CHECK); ?>,
bars: {
show: true,
barWidth: 0.5,
align: "center"
}
}
],
{
xaxis: {
ticks: [
[1, "excellent"],
[2, "good"],
[3, "average"],
[4, "bad"]
]
}
}
);
});
有没有人遇到过这样的事情?我的做法是错误的吗?任何帮助将不胜感激。
我也研究了很多,尽量不要重复发布,如果已经回答了这个问题,请原谅我。
在追加到数组之前替换值...
while($rows = mysql_fetch_array($result))
{
switch ($rows['flavor']) {
case 'excellent':
$number = 1;
break;
case 'good':
$number = 2;
break;
case 'average':
$number = 3;
break;
case 'bad':
$number = 4;
}
$dataset1[] = array($number, $rows['COUNT(flavor)']);
}
你的问题不是你认为的那样; json_encode()
试图通过保留原始PHP数据类型来做正确的事情,并且来自MySQL数据库的数据是字符串。
想要数字?找到这个位:
$dataset1[] = array($rows['flavor'],$rows['COUNT(flavor)']);
并将其更改为:
$dataset1[] = array($rows['flavor'],(int)$rows['COUNT(flavor)']);
我认为最好在javascript中对其进行排序,这样您就不会在两个位置对flavors to integers
映射进行硬编码:
dataForFlot = [];
ticksForFlot = [];
flavorToIntMap = {'excellent':1, 'good':2, 'average':3, 'bad':4}; // this is our data to tick mapping
originalData = [["average",1],["bad",1],["excellent",1],["good",2]]; // from your PHP
$.each(originalData, function(){ dataForFlot.push([flavorToIntMap[this[0]],this[1]]);});// convert the data to how flot wants it
$.each(flavorToIntMap, function(k,v){ticksForFlot.push([v,k]);}); // convert our mapping to the how flot wants the ticks