how to use json_encode - php

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"}]

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);

Loop through the database results and put the results in an array
JSON encode the array

Related

convert numerically indexed associative-array in PHP, to valid JavaScript Object via JSON

Let's say you have a numerically indexed array that looks like this (obtained via RedBeanPHP's find operation):
[
[33=>["name"=>"John", "age"=25]],
[55=>["name"="Jane", "age"=23]]
]
where 33 and 55 are id's of each of the 2 "beans" (basically associative-arrays).
And you want to convert the array to JSON so you can send it to a JavaScript client and use the data there as a JavaScript Object.
But you can't simply JSON_encode this because you'll end up with numerical keys in a JavaScript Object, and JavaScript doesn't like that.
What strategy can you use to convert this array to a JavaScript Object via JSON so that all the data (including id of each bean) is available at the JavaScript end? (To the RedBeanPHP folks out there: I'm hoping there's a native RedBeanPHP way to do this that I haven't found yet.)
One option is using array_map to loop thru the array. Use array_values to get all the values from the array and indexes the array numerically.
$arr = [
[33=>["name"=>"John", "age"=>25]],
[55=>["name"=>"Jane", "age"=>23]]
];
$result = array_map(function($o){
return array_values($o)[0];
}, $arr);
echo json_encode( $result );
This will result as:
[{"name":"John","age":25},{"name":"Jane","age":23}]
Simple. You should try this. First iterate through the outer array and inside that get the key i.e id of the data. Add id to other values and push that array into resultant one.
$result = array();
$arr = [[33=>["name"=>"John", "age"=>25]],[55=>["name"=>"Jane", "age"=>23]]];
foreach ($arr as $ar) {
foreach ($ar as $key => $value) {
$value['id'] = $key;
array_push($result, $value);
}
}
echo json_encode($result);
Output :-
[{"name":"John","age":25,"id":33},{"name":"Jane","age":23,"id":55}]
For your associative array:
$array = array(33 => array("name" => "John", "age" => 25), 55 => array("name" => "Jane", "age" => 23));
PHP json_encode function:
$good_json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Produces JSON for JavaScript object (string "name" : value pair):
{"33":{"name":"John","age":25},"55":{"name":"Jane","age":23}}

How to echo JSON doubly nested object literal w/ proper "headers"

I'm trying to simply echo a JSON object literal which includes every row in my database table.
As standard with the methods found in many other similar questions I looked at, I'm fetching every row and encoding it like so:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_array($result))
{
$rows[] = $r
//or: $rows[] = array('data' => $r);
}
echo json_encode($rows);
Similarly to the question PHP: can't encode json with multiple rows or mysql table to json ,
I want to echo a JSON Object which looks like this:
{
"data1": // how do I get "data1"?
{
name: John Smith,
title: Mr,
description: a man
}
}
{
"data2":{ // how do I get "data2"?
name:Bob Smith,
title: Mr,
description: another guy
}
}
Except I do not get how to achieve the "headers", the titles of the first level string of objects, such as "data1" or data2". In fact, my database table doesn't necessarily even have those values/that column.
This is what it looks like right now:
How can I get simply numerical "headers" like "1", "2" or "data1", "data2" without having to designate the "name" column as the "headers"? (Or do I have to have a column for that?)
My goal is to process the values in every "row" in the returned JSON.
I plan to use the jQ $.each function $.each(data, function(dataNum, dataInfo) -- e.g. data1 would be passed to dataNum and the values would be passed to dataInfo -- and be able to access specific table values by dataInfo.name, which right now is not working.
Thanks to any help in advance!
I would think you are way better off using mysqli_fetch_object() to get each row as it own object. When you then json_encode $rows you would have an array of objects.
Here is the code:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_object($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Your JSON would look like this:
[
{
"name":"Some Name",
"title":"Some Title",
"description":"Some description"
},
{
"name":"Some Other Name",
"title":"Some Other Title",
"description":"Some other description"
},
...
]
In javascript, that gives you an integer-indexed array of objects. So your javascript might look like this:
var array = JSON.parse(jsonString);
$.each(array, function(key, value) {
alert(key); // numerical index
alert(value.name); // name
alert(value.title); // title
alert(value.description); // description
});
Create indexes in your $rows variable:
<?php
$t['a'] = array ('name' => 'foo');
$t['b'] = array ('name' => 'bar');
echo json_encode ($t);
?>
In your case, a simple integer should do the trick, or something like $rows['data' . $i] followed by a $i++.

How to filter JSON array into PHP array

I have a JSONArray generated in java and I post it to one of my PHP files where it's saved to a file. From there it gets read and I need to generate a chart based on this data. All I need is to convert my raw JSON which has values I don't need, into a simply php array.
[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]
Is an example of 2 elements inside my JSON array. What I need todo is filter those values into arrays accordingly.
For example get how many votes a 'player' has, I need to add up how ever many elements are in the JSONArray, because 1 element is 1 vote (the id is primary auto-increment in my mysql DB, not located on my webserver)
I'd like the array to be to [player, votes] so when I echo the array it will be easily parsed by the google chart tools I'm using. I've spent the last 5 hours working on this and I've been stuck, thanks for any help!
To decode the JSON into a php array, you can do:
$json_array = json_decode($raw_json);
Then, to get the number of votes for each player out of the array:
$player_votes = array_reduce($json_array,
function($v, $item) {
if(!array_key_exists($item->player, $v))
$v[$item->player] = 1;
else
$v[$item->player] = 1 + $v[$item->player];
return $v;
}, array());
If I understand your question correctly, this will work.
EDIT: Updated the second code snippet
Try this :
$str = '[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]';
$res = array();
foreach(json_decode($str,true) as $val){
if(array_key_exists($val['player'],$res)){
$res[$val['player']] = $res[$val['player']]+1;
}
else{
$res[$val['player']] = 1;
}
}
echo "<pre>";
print_r($res);
Output :
Array
(
[Orangeguy24] => 2
)

How to format JSON output to display only values in quotes and not keys?

This is related to Need to display only array value in JSON output asked earlier.
I just want to show only values like
[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];
Background:
I am using and AJAX call via Jquery mobile to retrieve data from server (language:PHP). I want to use https://github.com/commadelimited/autoComplete.js in my Phonegap Application.
Please advice! I am new to JSON.
when using json_encode, any array that has a zero based numeric index (meaning it is not an associative array and starts with 0 and is not missing any numbers) will be converted to a javascript array instead of a js object literal. You can use array_values in php to get all the values from an array numerically indexed.
<?php
//a generic array
$a = array(
'foo'=>'bar',
'one'=>'two',
'three'=>'four');
//display the array in php
var_dump($a);
echo '<br>';
//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';
//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);
http://codepad.viper-7.com/hv06zn
Thanks Jonathan.
However I found the solution as below. I hope that it is useful to someone else too.
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row["title"];
}
mysql_close($con);
echo json_encode($records);

PHP json_encode return rows as arrays instead of objects

From my experience, when I json_encode data from a mysql table, the output is an object containing each row as an object within. What I want to do is to get each row as an array, like the example below (don't need the column names in there). How can I do that?
{ "Data": [
["1","Internet Explorer 4.0","Win 95+","4","X","1"],
["2","Internet Explorer 5.0","Win 95+","5","C","2"],
["3","Internet Explorer 5.5","Win 95+","5.5","A","3"],
["4","Internet Explorer 6","Win 98+","6","A","4"],
] }
Use mysql_fetch_row [docs] to get each row. This will get a row as a numerical array and those are also encoded as JSON arrays:
$data = array();
while(($row = mysql_fetch_row($result))) {
$data[] = $row;
}
echo json_encode(array('Data' => $data));
NOT CHECKED in interpreter:
You can change the type of variable by simple types convertion:
$data = DB::get('SELECT * FROM `table` WHERE 1');
echo json_encode(array('Data' => (array)$data));
Also you can use next function: array mysql_fetch_array ( resource $result [, int $result_type ] )

Categories