turtledude01 turtledude01 - 6 months ago 20
JSON Question

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do

json_encode()


On a single array, i get valid json, but if i do something like

$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);


It will return invalid json like so:

["{"key":"name"}"]


The expected outcome is

[{"key":"name"}]


I have searched for hours trying to find what is going on.

Answer

Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.

The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.

$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);

Following this code, $json will have the following value

{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}

It could then be parsed properly by javascript using jQuery.parseJSON()

Comments