Jump to content

json_encode for google charts


Michael_Roempel

Recommended Posts

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>	
	

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.