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:
 [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-2014 The PHP Group
All rights reserved.
Last updated: Mon Apr 21 02:02:11 2014 UTC