如何将PHP数组编码为JSON数组而不是对象? [英] How do I encode a PHP array to a JSON array, not object?

查看:132
本文介绍了如何将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"
  }
}

编码后的字符串如下:

{"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 world中的一个对象.如果您未设置严格的顺序(即从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数组而不是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆