简体   繁体   English

如何将2维PHP数组编码为Javascript数组?

[英]How to encode 2 dimentional PHP array to Javascript Array?

Here's my problem, i have a php array like this: 这是我的问题,我有一个像这样的PHP数组:

$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: 在将数组编码为json后,我得到了这个:

$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: 我想要的是将PHP数组传递给Javascript,以便JS看起来像这样:

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

Thanks in advance... 提前致谢...

Which version of PHP are you using ? 您使用的是哪个版本的PHP?

With PHP 5.2.10, I get what you're asking for : 使用PHP 5.2.10,我得到你所要求的:

$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 至少,这是没有JSON_FORCE_OBJECT选项 - 在PHP 5.3中添加


Maybe you can find something interesting in the user notes on the json_encode manual page ? 也许你可以在json_encode手册页上的用户注释中找到一些有趣的东西?

For instance, simoncpu says : 例如, simoncpu说

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. 需要注意的是:如果您想知道为什么json_encode()将您的PHP数组编码为JSON对象而不是JSON数组,您可能需要仔细检查数组键,因为json_encode()假定您的数组是对象(如果您的键)不顺序。

And if you search for json_encode+array+object on PHP's bugtracker, maybe you'll get some interesting result ? 如果你在PHP的bugtracker上搜索json_encode + array + object ,也许你会得到一些有趣的结果?
(For instance, something that says this was a bug, which has been corrected in recent versions of PHP ?) (例如,有人说这是一个错误,在最近的PHP版本中已经纠正过?)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM