I'm having one heck of a time here, how can I draw up the chart from a json_encoded mySQL array?
Data Retrieval (simply associated array from a PDO query):
if($cCt > 0){
header('Content-Type:application/json');
$table['cols'] = array(
array('id'=>'Date', 'label'=>'Date', 'type'=>'string'),
array('id'=>'Carbs', 'label'=>'Carbs', 'type'=>'number'),
array('id'=>'Sugar', 'label'=>'Sugar', 'type'=>'number'),
array('id'=>'Units', 'label'=>'Units', 'type'=>'number'));
for($i=0; $i<$cCt; ++$i){
$W = (isset($_GET['which'])) ? (int)$_GET['which'] : 0;
switch($W){
case 1: // weekly
case 2: // monthly
case 3: // yearly
$date = date('m/d', strtotime($CNums[$i]['Date']));
break;
case 4: // daily
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
default:
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
}
$rows[] = array('c'=>array('v'=>$date, 'v'=>$CNums[$i]['Carbs'], 'v'=>$CNums[$i]['Sugar'], 'v'=>$CNums[$i]['Units']));
}
$table['rows'] = $rows;
echo json_encode($table, JSON_NUMERIC_CHECK);
}else{
echo ErrorBox('Please login to see your charts.');
}
Code Attempt:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var $dUrl = "/assets/php/charts/chart.data.php?_=<?php echo time(); ?>&which=<?php echo (isset($which)) ? $which : 4; ?>&d=<?php echo (isset($d)) ? $d : null; ?>&dl=<?php echo (isset($dl)) ? $dl : null; ?>";
jQuery.getJSON($dUrl, function(d){
// Create a new blank DataTable
var data = new google.visualization.DataTable(d);
// Create our columns
/*
data.addColumn('date', 'Date');
data.addColumn('number', 'Carbs');
data.addColumn('number', 'Sugar');
data.addColumn('number', 'Units');
// Create our Rows
jQuery.each(d, function(i) {
data.addRows([d[i].Dates, d[i].Carbs, d[i].Sugar, d[i].Units]);
});
*/
var options = {
'colors': ['red', 'blue', 'yellow'],
'width': '98%',
'height': 280,
'backgroundColor': 'none',
'hAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'vAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'legendTextStyle': {fontName: 'Calibri',
fontSize: '12'}
};
//var chart = new google.visualization.ColumnChart(document.getElementById('<?php echo $where; ?>'));
var chart = new google.visualization.ColumnChart(document.getElementById('weekly_chart_div'));
chart.draw(data, options);
}).fail(function(msg){console.log('Error pulling in the data.' + msg);});
}
</script>
Original JSON from the $dUrl:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"string"},
{"id":"Sugar","label":"Sugar","type":"string"},
{"id":"Units","label":"Units","type":"string"}],
"rows":[["08\/23","40.0000000","256.0000000","9.0000000"],
["08\/24","33.8333333","102.5000000","4.6666667"],
["08\/25","38.2000000","290.2000000","10.6000000"],
["08\/26","36.0000000","322.0000000","12.0000000"],
["08\/28","23.6666667","348.3333333","9.6666667"],
["08\/29","31.3333333","214.1666667","7.3333333"],
["08\/30","16.0000000","154.0000000","4.0000000"]]}
New JSON after Data Retrieval Update:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"number"},
{"id":"Sugar","label":"Sugar","type":"number"},
{"id":"Units","label":"Units","type":"number"}],
"rows":[{"c":{"v":9}},{"c":{"v":4.6666667}},{"c":{"v":10.6}},{"c":{"v":12}},{"c":{"v":9.6666667}},{"c":{"v":7.3333333}},{"c":{"v":4}}]}
Yes, right now I am getting an error this.J[a].c is undefined, but it only shows where the chart should be loaded...not in FireBug
What I am aiming for is something like this:
example: http://o7th.com/Image3.png
Your rows are not formatted correctly. Rows is an array of objects, where each object has a "c" (array of cells) and an optional "p" (properties object) parameters. The array of cells is an array of objects with "v" (column data type, value of cell) and optional "f" (string, formatted value of cell) and "p" (parameters object) properties.
As an example, your first row of data should look like this:
{"c":[{"v":"08\/23"},{"v":40,"f":"40.0000000"},{"v":256,"f":"256.0000000"},{"v":9,"f":"9.0000000"}]}
In order to generate that from a JSON encoded PHP array, the array would have to look like this:
$row = array(
'c' => array(
array('v' => '08\/23'),
array('v' => 40, 'f' => "40.0000000"),
array('v' => 256, 'f' => "256.0000000"),
array('v' => 9, 'f' => "9.0000000")
)
);
By default, MySQL outputs all numbers as strings, so you need to cast them as ints or floats in order for them to be output as numbers, like this:
$foo = '33.333333'; // $foo == '33.333333'
$bar = (int) $foo; // $bar == 33
$cad = (float) $foo; // $cad == 33.333333
You can change or remove the formatted values if you don't want them (they are what will appear in the tooltips of the chart).
Edit:
You need to give each cell it's own array in the cells array; try this:
$rows[] = array(
'c'=>array(
array('v'=>$date),
array('v'=>$CNums[$i]['Carbs']),
array('v'=>$CNums[$i]['Sugar']),
array('v'=>$CNums[$i]['Units'])
)
);
Related
I've been struggling for a few days trying to convert a datetime string to a json datetime for inclusion in a Google Chart and am now looking for some help.
The format of the date I have is "2008-01-15 14:30:45" which I believe needs to be converted to Date(2008, 0, 15, 14, 30, 45) before being inserted into an array and then being converted to JSON format for a google chart.
The goal is primarily to be able to add a trendline to the graph but it would be nice to have the timescale correct too :).
Code follows.
Any help greatly appreciated.
SteveW
<?php
require_once 'dbconfig.php';
/* Your Database Name */
$dbname = 'speedtest';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//DOWNLOAD CHART
$dresult = $conn->query('SELECT starttime, download FROM speeddata');
$drows = array();
$dtable = array();
$dtable['cols'] = array(
// Labels for your chart, these represent the column titles.
array('label' => 'StartTime', 'type' => 'string'), //change 'string' to datetime
array('label' => 'Download Speed', 'type' => 'number'),
);
/* Extract the information from $result */
foreach($dresult as $d) {
$dtemp = array();
// the following line will be used to slice the chart
$dtemp[] = array('v' => $d['starttime']); //starttime to Date(2008, 0, 15, 14, 30, 45) format?
// Values of each slice
$dtemp[] = array('v' => (DOUBLE) $d['download']);
// $temp[] = array('v' => (DOUBLE) $r['server_name']);
$drows[] = array('c' => $dtemp);
}
$dtable['rows'] = $drows;
// convert data into JSON format
$djsonTable = json_encode($dtable);
//echo $djsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--Reload page on resize-->
<script type="text/javascript">
var currheight = document.documentElement.clientHeight;
window.onresize = function(){
if(currheight != document.documentElement.clientHeight) {
location.replace(location.href);
}
}
</script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(downloadChart);
function downloadChart() {
// Create our data table out of JSON data loaded from server.
var ddata = new google.visualization.DataTable(<?=$djsonTable?>);
var options = {
//title: 'Speedtest Data',
//titleposition: 'none',
is3D: 'true',
width: '100%',
height: 500,
hAxis:{title: 'Time',
direction:1,
slantedText:true,
slantedTextAngle:90,
textStyle : { fontSize: 8} // or the number you want
},
vAxis:{title: 'Speed Mbit/s'},
legend: { position: 'bottom' },
chartArea: { top: 45, height: '40%',
backgroundColor: {
stroke: '#ccc',
strokeWidth: 1},
}
//trendlines: { 0: {color: 'green',} } // Draw a trendline for data series 0.
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('download_chart_div'));
chart.draw(ddata, options);
}
</script>
</head>
<body class="site">
<main class="site-content">
<!--this is the div that will hold the chart-->
<div id="chart_title">Download Speed</div>
<div id="download_chart_div"></div>
<hr><br>
</main>
</body>
</html>
Just try this
echo date('Y, m, d, G, i, s', strtotime('2008-01-15 14:30:45'));
In your code will look like this
$dtemp[] = array('v' => date('Y, m, d, G, i, s', strtotime($d['starttime']));
The following ended up doing what was required to insert a datetime extracted from a mysql database into a google chart. I'm positive that there is a more elegant way but it works! :)
The function goes at the start of the php
function JSdate($in,$type){
if($type=='date'){
//Dates are patterned 'yyyy-MM-dd'
preg_match('/(\d{4})-(\d{2})-(\d{2})/', $in, $match);
} elseif($type=='datetime'){
//Datetimes are patterned 'yyyy-MM-dd hh:mm:ss'
preg_match('/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/', $in, $match);
}
$year = (int) $match[1];
$month = (int) $match[2] - 1; // Month conversion between indexes
$day = (int) $match[3];
if ($type=='date'){
return "Date($year, $month, $day)";
} elseif ($type=='datetime'){
$hours = (int) $match[4];
$minutes = (int) $match[5];
$seconds = (int) $match[6];
return "Date($year, $month, $day, $hours, $minutes, $seconds)";
}
}
$presult = $conn->query('SELECT starttime, server_ping FROM speeddata');
$prows = array();
$ptable = array();
$ptable['cols'] = array(
// Labels for your chart, these represent the column titles.
array('label' => 'StartTime', 'type' => 'datetime'),
array('label' => 'Ping', 'type' => 'number'),
//array('label' => 'Ping', 'type' => 'number')
);
/* Extract the information from $result */
foreach($presult as $p) {
$date = JSdate($p['starttime'],datetime);
//echo JSdate($p['starttime'],'datetime');
$ptemp = array();
// the following line will be used to slice the chart+
$new_value = array();
for ($i=0; $i < count($new_value);
$i++): array_push($new_value, $date[$i]);
endfor;
$ptemp[] = array('v' => $date);
$prows[] = array('c' => $ptemp);
}
I tried to find a solution less complicated at your issue. I've send a JSON response in PHP thanks to JSONResponse in Symfony. The little trick I've made in PHP¨is to transform the dateTime to 'Y, m , d' format.
$tableTimeline = [];
foreach ($resources as $resource)
{
if($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0] != null)
array_push($tableTimeline, [
$resource->getTechnician()->getUsername(),
$resource->getBusiness()->getName()." (".$this->get('platform.gantt')->baseTime($resource->getBusiness())." h/s)",
// format -> new Date(1809, 3, 26)
date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0], 'Y, m, d'),
date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[1], 'Y, m, d'),
]);
}
return new JsonResponse($tableTimeline);
Then I retrieved the data in JS thanks to an Ajax call and modify the JSON object to an array
success: function (chart_values) {
let arrayData = $.map(chart_values, function (value, index) {
return [value];
});
arrayData = changeToDate(arrayData);
draw_chart(arrayData); // call your drawing function!
}
The little trick of this code is located in the changeToDate function -> I changed the values of the 2 & 3 columns from string dates ('Y, m,d') to readable JS dates
function changeToDate(arrayData) {
arrayData.forEach(data => {
let startDate = new Date(data[2]);
let endDate = new Date(data[3]);
data[2] = startDate;
data[3] = endDate;
});
return arrayData;
}
Then I drew the chart thanks to draw_chart function
I am trying to create a google chart with column labels. The following works just fine for me. Except that when i try to use it with a Json datacreated from a mysql table. Would you guys kindly help me out to understand where i am doing wrong.
Working Google Chart code:
<script type="text/javascript">
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['From', 'TotalOrders', 'Quantity'],
['Wk of 9/7/14', 172, 8910],
['Wk of 9/14/14', 121, 5901],
['Wk of 9/21/14', null, null],
['Wk of 9/28/14', null, null]
]);
var formatter = new google.visualization.NumberFormat( {pattern:'#,###'});
formatter.format(data, 1);
formatter.format(data, 2);
mydiv = $("#mychart");
chart = new google.visualization.ComboChart(mydiv[0]);
chart.draw(data, {
width: 600, height: 400, seriesType: 'bars',
chartArea: {left: 60, top: 30, width: 540}
});
rects = mydiv.find('svg > g > g > g > rect');
var row = 0;
for (i = 0; i < rects.length; i++) {
el = $(rects[i]);
if (parseFloat(el.attr("height")) <= 2) { continue; }
aparent = el.parent();
do { // skips 'null' values
text = data.getValue(row++, 1);
} while (text == null && row < data.getNumberOfRows());
if (text) {
text = formatter.formatValue(text);
// see below
pos = getElementPos(el);
attrs = {x: pos.x + pos.width / 2, y: pos.y - 2,
fill: 'black',
'font-family': 'Arial', 'font-size': 11,
'text-anchor': 'middle'};
aparent.append(addTextNode(attrs, text, aparent));
}
}
}
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawVisualization);
function getElementPos($el) {
return {
x: parseInt($el.attr("x")),
width: parseInt($el.attr("width")),
y: parseInt($el.attr("y")),
height: parseInt($el.attr("height"))
}
}
function addTextNode(attrs, text, _element) {
var el = document.createElementNS('http://www.w3.org/2000/svg', "text");
for (var k in attrs) { el.setAttribute(k, attrs[k]); }
var textNode = document.createTextNode(text);
el.appendChild(textNode);
return el;
}
</script>
but when i use it with the following it doesn't work.
$table = array();
$table['cols'] = array(
array('label' => 'From', 'type' => 'string'),
array('label' => 'TotalOrders', 'type' => 'number'),
array('label' => 'Quantity', 'type' => 'Number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['From']);
$temp[] = array('v' => (int) $r['TotalOrders']);
$temp[] = array('v' => (int) $r['Quantity']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
I can't seem to find what is going wrong here. perhaps you guys will be able to point me to the right direction.
That JSON structure is not compatible with the arrayToDataTable function - you must use the regular DataTable constructor:
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
Also, you should have the json_encode function parse numbers correctly in the output, otherwise they may come out as strings:
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
I am creating a Google charts bar chart! The data comes from MySQL, using JSON and PHP.
All I would like is to put labels at the end of Bar charts. Because data are dynamic, i found it difficult.
<?php
$sth = mysql_query("select * from table");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$temp = array();
$temp[] = array('v' => (string) $r['Stats']);
$temp[] = array('v' => (int) $r['Value']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
legend: {position: 'none'},
bar: {groupWidth: "85%"},
colors:['#4A9218'],
hAxis: {
viewWindowMode: 'explicit',
viewWindow: {
max: 400,
min: 0,
},
gridlines: {
count: 10,
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" style="width:100%; height:200px"></div>
Outcome :
Bar chart with no labeling
Outcome I am looking for:
Bar chart with labeling at the end on the right
First, add JSON_NUMERIC_CHECK to your json_encode call, as MySQL outputs numbers as strings, and inputting numbers as strings can cause problems with some charts:
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
If you want to add the data values as annotations on the bars, the easiest way is to create a DataView that includes a calculated 'annotation' role column that takes its data from the value column and stringifies it:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
Then use the view to draw your chart instead of the DataTable:
chart.draw(view, options);
I'm trying to draw a chart with google charts API. One column contains dates, the other one contains numbers.
This is the php page to get my data:
<?php
include 'core/init.php';
$result = mysql_query('SELECT amountDone, resultDate FROM result');
$table = array();
$table['cols'] = array(
array('label' => 'Done', 'type' => 'number'),
array('label' => 'Date', 'type' => 'date')
);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$temp = array();
$temp[] = array('v' => (int)$r['amountDone']);
$temp[] = array('v' => $r['resultDate']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
The json data returned is the following:
{"cols":[{"label":"Done","type":"int"},{"label":"Date","type":"date"}],"rows":[{"c": [{"v":1200},{"v":"2013-07-25"}]},{"c":[{"v":3600},{"v":"2013-07-26"}]}]}
In my main page I try to draw the chart with the following code:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "get_json.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
But I always get the following error (depends on the browser I use but they contain the same information I guess, this one is chrome):
Object 2013-07-25 has no method 'getTime
Anybody an idea what this could mean because I don't get a single other error
Thanks in advance!
changed my query to:
$result = mysql_query("SELECT DATE_FORMAT(resultDate, '%W, %D %M %Y') as Datum, SUM(amountDone) as AmountD, SUM(amountToDo) as AmountT
FROM result
GROUP BY resultDate");
and the type is now string. Works like a charm. :)
I am working with the google chart visualization API.
I have a variable in php:
`$value`
which contains the following:
['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]
I want to use this $value below in data.addRows as follows however the output I am getting is blank
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Period');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
<?php echo $value ?>
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
After some research it seems it is Ajax I am trying to attempt. Is this correct? Is there a simple way I can return the value $value to data.addRow??
Here is the process to which $value is set:
$i = "0";
$period = "0";
$chartrow = array();
$unitpriceNumR = 3
while ($i<3)
{
$chartrow[$i] = "['".$period."',".$sPrice[$i].", ".$uPrice[$i]."]";
$period++;
$i++;
}
switch ($currentStage)
{
case "0":
$value = $chartrow[0];
break;
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
}
In this example if $currentStage = "2" then $value is set to ['0',0, 0],['1',65, 35]
Ok now I have even tried a copy and paste of google code into my file and still no success of seeing a graph. (code taken from:http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html)
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Using this code
$chartrow = array();
for ($i = 0; $i < 3; $i++ )
{
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
echo $chartrow;
}
results in $chartrow displaying the word "Array" to the screen.
Please have a look at the JSON encode function provided with PHP. This will let you echo or print out a JSON encoded string that JavaScript transforms into a native object.
$value = array(
array('0', 0, 0),
array('1', 65, 35),
array('2', 88, 35),
...
);
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
EDIT
$i = 0;
$chartrow = array();
$unitpriceNumR = 3
for (; $i < 3; $i++ )
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array_slice($chartrow, 0, 2);
default:
// You should have some default value, seriously!!!
}
// Then go the json_encode way, it's safer and easier to maintain!
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
Change [<?php echo $value ?>] to <?php echo json_encode($value) ?>
echo $value produces Array(5) because PHP doesn't natively know how to represent an array as a string.
echo json_encode($value) produces:
[['0',0, 0],['1',65,35],['2',66,35],['4',35,35],['5',99, 100]]
so you don't need brackets around the <?php ... ?>.
http://php.net/manual/en/function.json-encode.php
EDIT: thanks for clarifying how the PHP variables are formed.
The problem is that you're manually converting arrays into strings, when you should let $json_encode do all of the work for you.
Revised version of the PHP code:
$chartrow = array();
$unitpriceNumR = 3;
for ($i=0; $i<=2; $i++)
$chart_row[$i] = array($i, $sPrice[$i], $uPrice[$i];
switch ($currentStage)
{
case '0':
case '1':
$value = $chartrow[0];
break;
case '2':
$value = array($chartrow[0], $chartrow[1]);
break;
}
EDIT2: I tried what you did (replacing the php block with what we expect the php block to produce) and it didn't work for me either. Firebug says 'Container is not defined' in Google's own code.
You forgot to add a div to your document. Add <div id='chart_div'></div> after the script.
So we're on the same page: http://jsfiddle.net/daemon/nnpeE/
Here is the answer to this problem
PHP: How to pass multiple variables to an array?
Whenever I have values like that I do this as my first script on the page and it seems to work for me. It also allows me to inspect what is going on with the PHP instead of the variable being hidden in some function. Note that this will create a global variable which might be not what you want.
<script>
var a = [<?php echo($var1) ?>];
</script>
EDIT:
I got your PHP code to work for me. The changes I made was I converted $i to just 0 not "0" The same goes for the switch statement . Also line 4 needs a semicolon after it. Then I put this
<script>
var a = [<?php echo($value) ?>];
</script>
And the output in the page was
<script>
var a = [['0',, ],['1',, ]];
</script>