up vote 0 down vote favorite

Here's my problem, i have a php array like this:

$output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3));

after the array was encoded to json i got this:

$output = {"1":[1,1,1,1],"2":[2,2,2,2],"3":[3,3,3,3]}

all i want is to pass the PHP array to Javascript so that the JS looks like this:

var output = [[1,1,1,1],[2,2,2,2],[3,3,3,3,]];

Thanks in advance...

flag

79% accept rate

2 Answers

up vote 3 down vote

Which version of PHP are you using ?

With PHP 5.2.10, I get what you're asking for :

$output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3));
$json = json_encode($output);

echo $json . "\n";

Outputs :

$ php temp.php
[[1,1,1,1],[2,2,2,2],[3,3,3,3]]


At least, this is without the JSON_FORCE_OBJECT option -- that was added in PHP 5.3


Maybe you can find something interesting in the user notes on the json_encode manual page ?

For instance, simoncpu says :

A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

And if you search for json_encode+array+object on PHP's bugtracker, maybe you'll get some interesting result ?
(For instance, something that says this was a bug, which has been corrected in recent versions of PHP ?)

link|flag
+1 for JSON_FORCE_OBJECT – LiraNuna Feb 12 at 5:19
what do you mean by +1, I use 5.2 version of PHP... – Trez Feb 12 at 5:24
i think there was an error in json_encode in multi-dimentional array...any ideas? – Trez Feb 12 at 5:28
Wow, Trez. Shame on you for treating a good answer so carelessly. – Adam Backstrom Feb 12 at 5:31
@adam, can u give me other solutions so that it will work in version 5.2.1 – Trez Feb 12 at 5:37
show 1 more comment
up vote 0 down vote

Your original solution works for me:

adam@fsck:~:0$ php -r 'echo json_encode(array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3)));'
[[1,1,1,1],[2,2,2,2],[3,3,3,3]]
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.