php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45162 JSON does not properly encode Arrays
Submitted: 2008-06-03 15:35 UTC Modified: 2008-06-05 18:23 UTC
From: christopher dot nagle at umb dot edu Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.6 OS: Windows XP/ Ubuntu
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
26 + 22 = ?
Subscribe to this entry?

 
 [2008-06-03 15:35 UTC] christopher dot nagle at umb dot edu
Description:
------------
After manipulating arrays using [] or creating an array in the form array("key" => value, ...) or calling unset on an array element. json_encode will encode the array as an object rather than an array.

Reproduce code:
---------------
echo json_encode(array(1 => new stdClass(), 2 => new stdClass(), 3 => new stdClass()));
$m = array();
$m[1] = new stdClass();
$m[2] = new stdClass();
$m[3] = new stdClass();
echo json_encode($m);
$m = array_values($m);
echo json_encode($m);
unset($m[0]);
echo json_encode((array) $m);


Expected result:
----------------
["1":{},"2":{},"3":{}]
["1":{},"2":{},"3":{}]
[{},{},{}]
["1":{},"2":{}]

Actual result:
--------------
{"1":{},"2":{},"3":{}}
{"1":{},"2":{},"3":{}}
[{},{},{}]
{"1":{},"2":{}}

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-06-05 18:23 UTC] jani@php.net
This is totally expected behaviour. Please read this:
http://www.json.org/

Note: array and assoc-array are different things. Latter being "object" in json.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 09:01:28 2024 UTC