How do I encode a PHP array to a JSON array, not object?(如何将 PHP 数组编码为 JSON 数组,而不是对象?)
问题描述
我正在尝试对从 Zend_DB 查询返回的数组进行 json_encode.
I am trying to json_encode an array which is returned from a Zend_DB query.
var_dump 给出:(手动添加 0 个成员不会改变图片.)
var_dump gives: (Manually adding 0 member does not change the picture.)
array(3) {
[1]=>
array(3) {
["comment_id"]=>
string(1) "1"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[2]=>
array(3) {
["comment_id"]=>
string(1) "2"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[3]=>
array(3) {
["comment_id"]=>
string(1) "3"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "jhghjg"
}
}
编码后的字符串如下所示:
The encoded string looks like:
{"1":{"comment_id":"1","erasable":"1","comment":"test 1"},
"2":{"comment_id":"2","erasable":"1","comment":"test 1"},
"3":{"comment_id":"3","erasable":"1","comment":"jhghjg"}}
我需要的是:
[{"comment_id":"1","erasable":"1","comment":"test 1"},
{"comment_id":"2","erasable":"1","comment":"test 1"},
{"comment_id":"3","erasable":"1","comment":"jhghjg"}]
php.ini/json_encode 文档说它应该是什么样子.
Which is what the php.ini/json_encode documentation says it should look like.
推荐答案
您如何设置初始数组?
如果你这样设置:
array(
"1" => array(...),
"2" => array(...),
);
那么你没有一个带有数字索引的数组,而是字符串,在 JS 世界中它被转换为一个对象.如果您没有设置严格的顺序(即从 0 而不是 1 开始),也会发生这种情况.
then you don't have an array with numeric indexes but strings, and that's converted to an object in JS world. This can happen also if you don't set a strict order (i.e. starting at 0 instead of 1).
然而,这是在黑暗中拍摄,因为我看不到您的原始代码:首先尝试在不使用键的情况下设置您的数组:
This is a shot in the dark, however, because I can't see your original code: try setting your array without using keys at all in the first place:
array(
array(...),
array(...),
);
这篇关于如何将 PHP 数组编码为 JSON 数组,而不是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 PHP 数组编码为 JSON 数组,而不是对象?


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01