Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use json_encode

I'm dealing with highcharts with dynamic data (values retrieved from database). By writing a query i was able to retrieve the following data from the table

Item   2011   2012
pen     5      7
pencil  4      20
eraser  6      43

I want to store the above info in the following structure and pass it to another page

[{ name:'pen', data: [5,7]},{ name:'pencil', data: [4,20]},{ name:'eraser', data: [6,43]}]";

I want to push the above data to the drilldown highchart.

Is there a way i can generate in this format? I've tried using json_encode but unable to succeed. Can i achieve this using json_encode?

Updated I've tried in this way

while($row = mysql_fetch_assoc($result))
  {
  $rows[]= $row;

  }
echo json_encode($rows);

and got

[{"Item":"pen","2011":"5","2012":"7"},{"Item":"pencil","2011":"4","2012":"20"},{"Item":"eraser","2011":"6","2012":"43"}]
like image 573
Anil Avatar asked Apr 30 '12 01:04

Anil


People also ask

What is the use of json_encode?

The json_encode() function is used to encode a value to JSON format.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What is json_encode in codeigniter?

json_encode(mixed $value , int $flags = 0, int $depth = 512): string|false. Returns a string containing the JSON representation of the supplied value . If the parameter is an array or object, it will be serialized recursively.

What is json_encode and json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.


2 Answers

json_encode is a convenience method to convert an array into JSON format. To have the output you provided, you will need an array of arrays. Each sub-array has keys "name" and "data", where "name" is the Item column, and "data" is another array containing values from 2011 and 2012.

$results = mysql_query("...");
$arr = array();

while ($row = mysql_fetch_assoc($results))
{
    $name = $row['Item'];
    $data = array($row['2011'], $row['2012']);

    $arr[] = array('name' => $name, 'data' => $data);
}

echo json_encode($arr);
like image 127
Logan Serman Avatar answered Sep 17 '22 11:09

Logan Serman


  1. Loop through the database results and put the results in an array
  2. JSON encode the array
like image 21
John Conde Avatar answered Sep 17 '22 11:09

John Conde