PHP中的json问题总结

PHP中的json_encode会将一个带有键值的数组编码成一个对象,其实我们期望编码后的值依然是数组,结果导致js无法正常解析。

记得以前在网上看到过这样的总结,但忘记出处了,更忘记记下来了。于是又一次查询PHP手册。浪费时间呀。汗

If, for some reason you need to force a single object to be an array, you can use array_values() -- this can be necessary if you have an array with only one entry, as json_encode will assign it as an object otherwise :

<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}


<?php $encoded = json_encode(array_values($object)); ?>
output:
[{"foo": "bar", "12": "true"}]

if your keys are not sequential,Use array_values() to re-index the array。
如果你的键值不是连续的,使用array_values重建数组索引。


解决方法:json_encode(array_values($array));


300*300
 文章首页关于迷茫时代关于我写意人生
版权所有:迷茫时代 All rights reserved   
执行时间:0.00466 秒