php json_encode received at jquery end, lost order? - php

when i return a key pair array in php to ajax call at jquery (javascript) end the order i have maintain in php get lost. how to preserve array order.
e.g array('node' => 'abc', 'test' => 'xyz', 'a' => 'xyz') this array disorder to array('a' => 'xyz', 'node' => 'abc', 'test' => 'xyz') in jquery. Any help.

JavaScript has no concept of an associative array as in PHP, so when you JSON encode something, it becomes an object instead. The ordering of object keys isn't important, so relying on them could lead to unexpected behaviour.
If ordering is important, you should consider using a non-associative array with objects (or associative arrays) as values.
$myArray = array(
array('x' => 'node', 'y' => 'abc'),
array('x' => 'test', 'y' => 'xyz'),
array('x' => 'a', 'y' => 'xyz'),
);
That would encode as:
[
{"x": "node", "y": "abc"},
{"x": "test", "y": "xyz"},
{"x": "a", "y": "xyz"}
]

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

json_encode( json_encode (array) )

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

json_encode($array) reverse order of my php array

I have json_encode($array) it gives me a list in a different order on google chrome
array_reverse: used to Return an array with elements in reverse order, e.g:
$array = array_reverse($array);
echo json_encode($array,JSON_UNESCAPED_UNICODE);
The encoding is done on the backend by the PHP so Google Chrome has nothing to do with this issue.
Check your array order before you encode it.
check the value in $array using var_dump to make sure, thats the order you want.
Edit: look at the 3rd example in the manual
What does your JSON data look like? If:
{1,2,3}
Your browser will not necessarily preserve the order. But if formatted as a JSON array:
[1,2,3]
Then the order will be preserved.
If your array is associative, but indexed by integers (like $arr1 = ['3' => 'x', '2' => 'a', '1' => 'b'];), the browser (when parsing JSON) assumes that the keys of the array indicate the order in which the values are stored (as in a classical, non-associative array - like $arr2 = ['x','a','b'];).
See for yourself - compare the results of parsing the JSON generated from those two associative arrays - one is indexed by non-integer strings (A), the other one is indexed by integers (even if they are string-typed in PHP) (B).
For both examples the values in PHP are stored in order: 'x', 'a', 'b', and only the keys are different.
A) associative array, indexed by strings
<?php
$arr1 = [
'foo' => 'x',
'bar' => 'a',
'baz' => 'b'
];
$json = json_encode($arr1); // $json is now a string: '{"foo":"x","bar":"a","baz":"b"}'
And then, in the browser:
var jsonData = JSON.parse('{"foo":"x","bar":"a","baz":"b"}');
console.log(jsonData);
// prints {foo: "x", bar: "a", baz: "b"} - the keys are in different order then expected!
B) associative array, indexed by integers (even if they are strings in PHP!)
<?php
$arr1 = [
'3' => 'x',
'2' => 'a',
'1' => 'b'
];
$json = json_encode($arr1); // $json is now a string: '"{"3":"x","2":"a","1":"b"}"'
And then, in the browser:
var jsonData = JSON.parse('"{"3":"x","2":"a","1":"b"}"');
console.log(jsonData);
// prints {1: "b", 2: "a", 3: "x"} - the keys are in different order then expected!
As you see - the JSON parser assumes a classical array when the
indices are integers.
So if you need to maintain the order, I'd suggest switching to a classical array and perhaps adding an order / key field to the JSON (for sorting purposes - if you need it):
$arr1 = [
'3' => 'x',
'2' => 'a',
'1' => 'b'
];
$json = json_encode(array_values($arr1)); // note the array_values() here - but this way you loose the index keys
Another way:
$arr1 = [
'3' => [ 'key' => '3', 'value' => 'x'],
'2' => [ 'key' => '2', 'value' => 'a'],
'1' => [ 'key' => '1', 'value' => 'b'],
];
$json = json_encode(array_values($arr1));
// this way you have both values and keys,
// and the parsed JSON will be in the exact order you want it to be

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