Link to home
Start Free TrialLog in
Avatar of Steve Tinsley
Steve TinsleyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Create javascript array from php sql query for use with charts.js

I am using http://www.chartjs.org/ to create some bar charts. The data is coming from a php / sql query.

I need to get the php data into the js arrays but im not sure how.

This is as far as I have got:

<script type="text/javascript">
<?php foreach ($rows as $row) {
	extract($row); ?>
	console.log('<?= $questionOption; ?>');
	console.log('<?= $questionResponseCount; ?>');
<?php } ?>


$( document ).ready(function() {

	//EXAMPLE DATA
	var barData = {
		labels : ["January","February","March","April","May","June"],
		datasets : [
			{
				data : [203,156,99,251,305,247]
			}
		]
	}


    var canvas = document.getElementById('canvas').getContext('2d');
    new Chart(canvas).Bar(barData);
});
</script>

Open in new window


I hope you can help.

Steve
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Have you tried

echo "var data = " . json_encode($rows .';');

Open in new window


This might not work because the JSON structure that is output might not match what you are expecting in your JavaScript code in which case you might have to massage your PHP data.

What does your data look like in $rows - can you var_dump / print_r it so we can have a look.
Avatar of Steve Tinsley

ASKER

This is what I get returned:

Array ( [0] => Array ( [questionOptionID] => 60 [questionID] => 29 [questionOption] => Queen Mary [correctAnswer] => 1 [questionResponseCount] => 6 ) [1] => Array ( [questionOptionID] => 61 [questionID] => 29 [questionOption] => Queen Boudica [correctAnswer] => 0 [questionResponseCount] => 36 ) [2] => Array ( [questionOptionID] => 62 [questionID] => 29 [questionOption] => Queen Matilda [correctAnswer] => 0 [questionResponseCount] => 8 ) [3] => Array ( [questionOptionID] => 63 [questionID] => 29 [questionOption] => Queen Elizabeth I [correctAnswer] => 0 [questionResponseCount] => 3 ) )

Open in new window


and I need questionOption and questionResponseCount.
Here is a example for you,
<?php
$months=array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
$datasets = array(
  "dataset"=> array(
    array("data" => array (10,110,210,310,410,510), 
      "label" => "My First dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)"),  
    array("data" => array (20,120,220,320,420,520),
      "label"=> "My Second dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)"),  
    array("data" => array (30,130,230,330,430,530),
      "label"=> "My Third dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)")
    )
);

$jsonArray = array("months"=> $months, "datasets"=> $datasets);
echo json_encode($jsonArray,JSON_PRETTY_PRINT);
?>

Open in new window

You have to pick appropriate sql query/data columns for each data values
Here is an another example, showing how to build array and then output the json

            
$mydata = array(
  array("questionOptionID" => 10, "questionID" => 19,"questionOption" => "Question Option 1", "correctAnswer" => 1,"questionResponseCount" => 6),
  array("questionOptionID" => 20, "questionID" => 29,"questionOption" => "Question Option 2", "correctAnswer" => 1,"questionResponseCount" => 10),
  array("questionOptionID" => 30, "questionID" => 39,"questionOption" => "Question Option 3", "correctAnswer" => 2,"questionResponseCount" => 30),
  array("questionOptionID" => 40, "questionID" => 49,"questionOption" => "Question Option 4", "correctAnswer" => 3,"questionResponseCount" => 100),
  array("questionOptionID" => 50, "questionID" => 59,"questionOption" => "Question Option 5", "correctAnswer" => 3,"questionResponseCount" => 20)
);

echo json_encode($mydata,JSON_PRETTY_PRINT);

$qdata1 = array();
$qdata2 = array();

foreach ($mydata as $qdata) {
  echo "<h3>" .  $qdata['questionOption'] . ":" . $qdata['questionResponseCount'] .  "</h3>";
  array_push($qdata1,$qdata['questionOption']);
  array_push($qdata2,$qdata['questionResponseCount']);
}

$jsonArray = array(
  "labels"=> $qdata1, 
  "datasets"=> array(
  "data"=>$qdata2,
  "label"=> "My Third dataset",
  "fillColor"=> "rgba(220,220,220,0.5)",
  "strokeColor"=> "rgba(220,220,220,0.8)",
  "highlightFill"=> "rgba(220,220,220,0.75)",
  "highlightStroke"=> "rgba(220,220,220,1)")
);

echo json_encode($jsonArray,JSON_PRETTY_PRINT);

Open in new window

Firstly, not sure how the data dump you posted ties into Chart.js - did you dump the correct data? The data looks like a question structure for a survey type application.

Here is some sample code for how to get the Array data you posted into a JavaScript array - you can adapt if necessary
<!doctype html>
<html>
<body>
<?php
$rows = array ( 
array ( 
	'questionOptionID' => 60,
	'questionID' => 29, 
	'questionOption' => "Queen Mary", 
	'correctAnswer' => 1, 
	'questionResponseCount' => 6
	), 
array ( 
	'questionOptionID' => 61,
	'questionID' => 29, 
	'questionOption' => "Queen Boudica",
	'correctAnswer' => 0, 
	'questionResponseCount' => 36 
),
array ( 
	'questionOptionID' => 62, 
	'questionID' => 29, 
	'questionOption' => "Queen Matilda",
	'correctAnswer' => 0, 
	'questionResponseCount' => 8 
), 
array ( 
	'questionOptionID' => 63, 
	'questionID' => 29, 
	'questionOption' => "Queen Elizabeth I", 
	'correctAnswer' => 0, 
	'questionResponseCount' => 3 
	) 
);
$json = json_encode($rows);
echo $json;
echo <<< JSCRIPT
<script>
	var questions={$json};
</script>
JSCRIPT;
?>
<script>
console.log(questions);
</script>
</body>
</html>

Open in new window

Working sample here. Examine the console to see the output of the console.log(questions) that dumps the JavaScript array created by the PHP script.
ASKER CERTIFIED SOLUTION
Avatar of Member_2_248744
Member_2_248744
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial