Hello,
I am new to pHp and javascript languages and I am trying to do some math calculations in pHp, then display the results with google charts. However, I got stuck with inserting data from pHp using json_encode. It works for the most simple array, with using 2 values.
When using array of arrays, it does not work. I believe it could be a syntax errors with all those brackets but I could not figure it out.
Thanks for any ideas!
<?php
// some arrays with dim 2x2
$testarr0 = array( 0.1, 2.5);
$testarr = array( 1.0, 3.5);
$testarr = array( $testarr0, $testarr ) ;
// this is how it looks in pHp
$json = json_encode($testarr);
echo($json);
echo '<br/>';
echo json_encode($json);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x values');
data.addColumn('number', 'y1 ');
//var dataArray = <?php echo json_encode($testarr);?>;
//document.body.innerHTML = " Data Array with json: " + dataArray ;
// defining array here works well
/* data.addRows(
[
[0.1 ,2.5],
[1.0 ,3.5]
]
);
*/
// this here does not work:
data.addRow(
<?php echo json_encode($testarr);?>
);
// some options for the chart
var options = {
chart: {
title: 'Points over time',
},
width: 600,
height: 400,
axes: {
x: {
0: {side: 'top'}
}
}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
</head>
<body>
<div id="line_top_x" style="width: 900px; height: 500px"></div>
</body>
</html>