我有一个问题。对于学校项目,我们正在制作交易站点,因此我们需要一张图表。我们在图表中加载的数据将采用csv格式,因此我们需要将其解析为json格式。这是到目前为止的代码:
PHP:
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$data = file_get_contents("https://www.oursite.com/csv_get_data.php?method=graph&ratio=BTC&period=15m", false, stream_context_create($arrContextOptions));
$rows = explode("/r/l",$data);
$s = array();
foreach($rows as $row) {
$s[] = str_getcsv($row);
}
$dataPoints = array();
foreach($s as $row) {
$DateTime = $row[0];
$Open = $row[1];
$High = $row[2];
$Low = $row[3];
$Close = $row[4];
}
现在我们需要对数据进行格式化,因此它可以适合以下代码:
Javascript:
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'candlestick',
renderAt: 'chart-container',
width: '700',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"theme": "fusion",
"caption": "",
"subCaption": "",
"numberprefix": "$",
"vNumberPrefix": " ",
"pyaxisname": "Price",
"vyaxisname": "Volume",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"toolTipPadding": "5"
},
"categories": [{
"category": [{
"label": "5 days ago",
"x": "1"
}, {
"label": "Now",
"x": "507"
}]
}],
"dataset": [{
"data": [{
"open": "18.74",
"high": "19.16",
"low": "18.67 ",
"close": "18.99",
"x": "1",
}, {
"open": "18.74",
"high": "19.06",
"low": "18.54",
"close": "18.82",
"x": "2",
}, {
"open": "19.21",
"high": "19.3",
"low": "18.59 ",
"close": "18.65",
"x": "3",
}]
}]
}
});
fusioncharts.render();
});
数据继续包含许多数据点,但是对于示例而言,它们不是必需的。但是有人可以帮助我创建正确的json格式的数据集吗?
编辑:
在foreach中,我输入了以下行:
$dataset[] = array('Open' => $Open, 'High' => $High, 'Low' => $Low, 'Close' => $Close, 'x' => $DateTime);
然后在javascript中,我尝试了以下方法:
"dataset": [
<?php
echo json_encode(array('data' => $dataset));
?>
]
但这没有显示任何图形,我在做什么错了?
答案 0 :(得分:0)
您似乎并没有尝试过那么多,但是尝试使用以下内容来找到自己想要的位置。
首先,您实际上并没有将任何东西放入数组$dataPoints
中,而是
$dataPoints = array();
foreach($s as $row) {
$DateTime = $row[0];
$Open = $row[1];
$High = $row[2];
$Low = $row[3];
$Close = $row[4];
}
您应该尝试类似
$dataPoints = array();
foreach($s as $row) {
$dataPoints[] = array(
'DateTime' => $row[0],
'Open' => $row[1],
'High' => $row[2],
'Low' => $row[3],
'Close' => $row[4]
);
}
然后使用json_encode
将数组作为JSON回显非常简单echo json_encode($dataPoints);