问题
I have to show some results of an experiment in a line chart. I got it working for static data, but I want to make it dynamic.
So what I got:
I have a line charts:
var options = {
chart: {
renderTo: 'container',
type: 'line',
},
series: [{}]
}
I want something like this: http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/series/data-array-of-arrays/
I am struggling to make those data:
data: [
[0, 29.9],
[1, 71.5],
[3, 106.4]
]
in php side and send it jquery, and feed to my line chart. I am aware of JSON encoding, but how should I create and array in php in first place? And how should I encode it and give it to jquery and feed my line chart?
This is working so far with static data:
var arr = [[0, 15], [10, 50], [20, 56.5], [30, 46.5], [40, 22.1],
[50, 2.5], [60, 27.7], [70, 55.7], [80, 76.5]];
options.series[0].name = 'Occlusion';
options.series[0].data = arr;
var l = new Highcharts.Chart(options);
});
But I want arr to come from php.
Thanks in advance.
回答1:
If you want to create such format, you need to restructure them first. Consider this example:
<?php
// lets say you have a raw data like this
$php_values = array(
array(0, 15),
array(10, 50),
array(20, 56.5),
array(30, 46.5),
array(40, 22.1),
array(50, 2.5),
array(60, 27.7),
array(70, 55.7),
array(80, 76.5),
);
$temp = array();
// format each array
foreach($php_values as $key => $value) {
$temp[] = '['.implode(',', $value).']';
}
// then format the whole array
$formatted_values = '['.implode(',', $temp).']';
?>
<script type="text/javascript">
var values = <?php echo $formatted_values; ?>;
console.log(values);
</script>
Sample Output
Edit: as @SebastianBochan pointed out,
$formatted_values = json_encode($php_array)
works the same way (probably the best and cleanest way)
来源:https://stackoverflow.com/questions/23992247/how-to-feed-series-data-that-has-x-axis-and-y-axis-values-in-line-highcharts