json_encode( json_encode (array) ) - php

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format
var arr = [
[45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}],
etc.
];
My script is along the lines of
while ...
array_push(
$arrBubble,
array(
11,
123,
1236,
json_encode(
array('label' => $car, 'color' => 'skyblue')
)
);
}
echo json_encode($arrBubble);
The problem is that the result is
[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]
The double json_encode has encoded the object(?) as a literal string.
What's the best way to work around this?

There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.
var_dump(json_encode([
11,
123,
1236,
['label' => $car, 'color' => 'skyblue']
]));
Outputs the structure you want:
string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"

Related

Repetitive Data in JSON file

I want to repeat the unit and pcs sections in the JSON file.
For example:
$rows[] = array(
'unit' => 'Example',
'pcs' =>
array('1 for Example', '2 for Example'),
);
Result:
[
{"unit":"Example","pcs":["1 for Example","2 for Example"]}
]
How to do this type of JSON?
Target:
[
{"unit":"Example",
"pcs":
["1 for Example","2 for Example"]},
{"unit":"ExampleSecond",
"pcs":
["1 for ExampleSecond","2 for ExampleSecond"]}
]
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]

How to use json and php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().

Creating data for jqPlot using PHP

I am using http://www.jqplot.com/tests/pie-donut-charts.php which needs to have data given to it in the following format:
//JavaScript
var data = [
['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];
The data is generated serverside with PHP. I am manually creating the string as follows:
//PHP
$string.='["'.$row['name'].'",'.$row['count'].'],';
I would rather just create an array, and use json_encode() or something similar to create the data. Any suggestions how I would do so?
$array = array(
array(
"Heavy Industry",
12
),
array(
"Retail",
9
)
);
$json = json_encode($array);
var_dump($json); // "[["Heavy Industry",12],["Retail",9]]"

Pass array to javascript as array not JSON from PHP

First this is not a duplicate questions. I've looked through some similar problem and most of the answer is what I am using right now.
Here is the problem set up,
on PHP side
$array = array('name' => 'a', 'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20));
echo json_encode($array);
on the JS side
data = $.parseJSON(data); // data is the return from the php script
above
As you can see the $array['data'] is an associative array with numeric number as its key and sorted in order. While parsing into JSON, javascript altered the order of that array and sorted 0 and 1 as numeric key and put them to the head of the object.
I know this is standard behavior for certain browser such as chrome, and IE9.
I've read somewhere that people suggest stick with array strictly if I want to maintain the order of the array.
But my question is how do you feed back an array from PHP to javascript as an array instead of using json object? Or is there other solution to this kind of problem . Thanks for the input in advance.
Thanks for the input in advance
Use an array to maintain order, and then an object to create the map. There are two ways. I would suggest:
$array = array('name' => 'a', 'data' =>
array(
array('key' => 0, 'value' => 15),
array('key' => 0.25, 'value' => 18),
array('key' => 0.35, 'value' => 19),
array('key' => 1, 'value' => 20),
)
);
echo json_encode($array);
Which will give you the JSON:
{
"name": "a",
"data": [
{"key": 0, "value": 15},
{"key": 0.25, "value": 18},
{"key": 0.35, "value": 19},
{"key": 1, "value": 20}
]
}
Then you will have order but to look up a certain key will be more difficult. If you want that to be easy you can return a mapping object as well like this:
$array = array('name' => 'a', 'data' =>
array(
"0" => 15,
"0.25" => 18,
"0.35" => 19,
"1" => 20,
),
'order' => array("0", "0.25", "0.35", "1")
);
echo json_encode($array);
Which will give you:
{
"name": "a",
"data": {
"0": 15,
"0.25": 18,
"0.35": 19,
"1": 20
},
"order": ["0", "0.25", "0.35", "1"]
}
One of these two methods of returning your data should prove to be the most useful for your specific use case.
Actually, it's PHP that takes the "0" and "1" keys and makes them numeric keys. This has nothing to do with your JavaScript.
There isn't any real way to work around this, but ideally your code should not rely on such things as "what order the keys of an object are in". It may be a better idea, just from what I see here, to separate the data into an array of keys and an array of values, then zip them back together on the JS side.
I'd suggest another field for storing order.
$array = array('name' => 'a',
'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20),
'order'=> '0,0.25,0.35,1'
);
echo json_encode($array);

Help trying to generate tricky multidimensional array format

I'm having trouble trying to build an array in PHP which will output in the JSON format I am looking for. I will show you what I am trying to achieve and where I have got to so far:
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
I am looping through db results and trying to build arrays to output the above json, my php looks like this (which is obviously not right yet):
//build the data
$data = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
$illnesses[] = $data;
This code outputs the following json:
[
{
[
[{"x":2,"y":6},{"x":2,"y":6}],
[{"x":2,"y":6},{"x":5,"y":6}],
[{"x":4,"y":6},{"x":4,"y":6}]
]
}
]
Any pointers on this would be great!
Basically, if you know your desired JSON output already, you can simply json_decode it to get it's representation in PHP. The var_export function prints the structure in parseable format. You can also use print_r or var_dump to dump the structure though.
$json = <<< JSON
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
JSON;
var_export( json_decode($json) );
The above approach is universal. Just decode and dump the structure. Then assemble your code to create this structure and encode.
do this:
$data['data'] = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
Looking at the JSON string, you can see that:
it is an array (it is surrounded by [ and ])
each element is an object (surrounded by { and })
the objects have an element data that is itself an array
that array consists of two objects with an x and a y property
It is important to know that a JSON object is represented in PHP by an associative array (when json_encode()'ing, json_decode() has a specific parameter to use either a stdClass or an assoc. array).
So the php structure looks like this:
$data = array(
array('data' => array(array('x' => 3, 'y' => 0), array('x' => 10, 'y' => 0))
,array('data' => array(array('x' => 11, 'y' => 0), array('x' => 13, 'y' => 0))
,array('data' => array(array('x' => 12, 'y' => 1), array('x' => 17, 'y' => 1))
);

Categories