0
我是C3(和.js)的新手,但對它的功能非常感興趣並且非常興奮。C3:讀取PHP生成的JSON
我使用PHP來從MySQL拉一個數據集按照教程: http://www.d3noob.org/2013/02/using-mysql-database-as-source-of-data.html
我可以使用下面的代碼成功生成在PHP中JSON文件:
$myquery = "SELECT `date`, `close` FROM `data2`";
$query = mysql_query($myquery);
if (! $query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$output=json_encode($data);
echo $output;
?>
這將生成以下JSON:
[{"date":"1-May-12","close":"58.13"},{"date":"30-Apr-12","close":"53.98"},{"date":"27-Apr-12","close":"67.00"},{"date":"26-Apr-12","close":"89.70"},{"date":"25-Apr-12","close":"99.00"},{"date":"24-Apr-12","close":"130.28"},{"date":"23-Apr-12","close":"166.70"},{"date":"20-Apr-12","close":"234.98"},{"date":"19-Apr-12","close":"345.44"},{"date":"18-Apr-12","close":"443.34"},{"date":"17-Apr-12","close":"543.70"},{"date":"16-Apr-12","close":"580.13"},{"date":"13-Apr-12","close":"605.23"},{"date":"12-Apr-12","close":"622.77"},{"date":"11-Apr-12","close":"626.20"},{"date":"10-Apr-12","close":"628.44"},{"date":"9-Apr-12","close":"636.23"},{"date":"5-Apr-12","close":"633.68"},{"date":"4-Apr-12","close":"624.31"},{"date":"3-Apr-12","close":"629.32"},{"date":"2-Apr-12","close":"618.63"},{"date":"30-Mar-12","close":"599.55"},{"date":"29-Mar-12","close":"609.86"},{"date":"28-Mar-12","close":"617.62"},{"date":"27-Mar-12","close":"614.48"},{"date":"26-Mar-12","close":"606.98"}]
我的問題是,我有c3.js代碼不呈現圖表。不確定這是否是因爲JSON格式正確。
這是我使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<!-- Here are all the javascripts and css that you need, you can download them or linked them like here -->
<script type="text/javascript" src="d3.js"></script>
<script type="text/javascript" src="c3.js"></script>
<link href="c3.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="chart"></div>
<script>
var obj2 = ['<?php echo $output; ?>'];
var chart = c3.generate({
bindto: '#chart',
data: {
json: [
obj2
], // or URL
keys: {
// x: 'name', // it's possible to specify 'x' when category axis
value: ['close '],
}
},
axis: {
x: {
// type: 'category'
}
}
});
</script>
</body>
</html>
代碼這是結果我在圖表中得到: C3空白圖表 - http://imgur.com/SHPmVOb
任何幫助將衷心感謝,因爲我覺得,因爲這可能成爲學習C3的一大阻力。
謝謝
感謝您的支持。你的回答幫我解決了這個問題。我認爲它不是JSON,而是一個字符串。原來,我的SQL的日期格式是「dd-mmm-yy」格式。解決方案是在SQL端將日期更改爲「yyyy-mm-dd」。現在工作。 – Predica