1 Replies - 458 Views - Last Post: 08 August 2012 - 01:08 PM Rate Topic: -----

#1 Global Static Media  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 02-May 09

PHP/MySQL to JSON Format Problem

Posted 08 August 2012 - 12:58 PM

Hi guys. I am working on populating a Google chart with data from a MySQL database using JSON and PHP.

Google charts expects the JSON to be formatted in the following way:

 cols: [{id: 'task', label: 'Task', type: 'string'},
          {id: 'hours', label: 'Hours per Day', type: 'number'}],
 rows: [{c:[{v: 'Work', p: {'style': 'border: 7px solid orange;'}}, {v: 11}]},
          {c:[{v: 'Eat'}, {v: 2}]},
          {c:[{v: 'Commute'}, {v: 2, f: '2.000'}]}]};



If my PHP is set up as follows...

$data = array(
	    "cols" => array(
	        array("id"=>"", "label"=>"Topping", "pattern"=>"", "type"=>"string"),
	        array("id"=>"", "label"=>"Slices", "pattern"=>"", "type"=>"number")
	    ),
	    "rows" => array();
	);




How can I populate my "rows" array from a database using PHP while keeping an acceptable format for Google chart tools?
Thus far I am able to parse the data but the output is nothing like Google wants. It ends up looking like [{"number_of_toppings":"36"}].

Any help is GREATLY appreciated!!

Is This A Good Question/Topic? 0
  • +

Replies To: PHP/MySQL to JSON Format Problem

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 6488
  • View blog
  • Posts: 23,571
  • Joined: 12-June 08

Re: PHP/MySQL to JSON Format Problem

Posted 08 August 2012 - 01:08 PM

It's not that bad.. you can cobble something together with a for loop from your PDO results.


$return = pdo.execute select statement.


for each $row in $return

echo "{id: '" . $row["task1"] . "', label: '" . $row["task2"] . "', type: '" . $row["string"] . "'}";

next


THis is assuming you are returning data with columns called: "task1, task2, string".

As it is you are building up a string formatting with the column names you need.

Now clearly this isn't exactly what you need, but you can work your way there!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1