我正在尝试使用C3.js
创建条形图,并通过PHP从mySQL database
提取数据并返回JS as JSON
。
PHP代码搜索已排序的列并将所有相关列添加到一起以最终得到{category:name, total_purchased:value}
$category_data_sql = "SELECT `category`, `total_purchased` FROM `item` ORDER BY `category`";
$category_data_result = $mysqli->query($category_data_sql);
$data = array();
$key = 0;
foreach ($category_data_result as $item) {
$key = $item['category'];
if (!array_key_exists($key, $data)) {
$data[$key] = array(
'category' => $item['category'],
'total_purchased' => $item['total_purchased'],
);
} else {
$data[$key]['total_purchased'] = $data[$key]['total_purchased'] + $item['total_purchased'];
}
$key++;
}
print_r(json_encode($data));
生成的JSON输出为:
{
"BRACELET": {
"category": "BRACELET",
"total_purchased": 26
},
"SALESMAT": {
"category": "SALESMAT",
"total_purchased": 4
},
"TOPPING": {
"category": "TOPPING",
"total_purchased": 48
}
}
但是,我无法在图表中显示此数据。 以下代码工作正常,一切都按预期显示。
var json_data = (<?php echo json_encode($data); ?>);
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'category',
json: [
{
"category": "BRACELET",
"total_purchased": 26
},
{
"category": "SALESMAT",
"total_purchased": 4
},
{
"category": "TOPPING",
"total_purchased": 48
},
{
"category": "NECKLACE",
"total_purchased": 29
}
],
type: 'bar',
keys: {
x: 'category',
value: [ "total_purchased" ]
}
},
axis: {
x: {
type: "category"
}
},
bar: {
space: 0.25
}
});
但是一旦我使用变量json_data
或者我在生成的JSON数据中手动复制,我得到一个空白表,控制台中没有错误。
任何帮助将不胜感激。
在此先感谢,科林。
答案 0 :(得分:1)
您可以使用array_values()
将数组转换为数字类型:
$json_data = json_encode(array_values($data));