Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

zend framework - How do I encode a PHP array to a JSON array, not object?

I am trying to json_encode an array which is returned from a Zend_DB query.

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"}}

What I need is:

[{"comment_id":"1","erasable":"1","comment":"test 1"},
{"comment_id":"2","erasable":"1","comment":"test 1"},
{"comment_id":"3","erasable":"1","comment":"jhghjg"}]

Which is what the php.ini/json_encode documentation says it should look like.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How are you setting up your initial array?

If you set it up like:

array(
 "1" => array(...),
 "2" => array(...),
);

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(...),
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...