php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51635 casting json objects to array
Submitted: 2010-04-22 15:49 UTC Modified: 2010-04-22 17:28 UTC
From: joel dot gaehwiler at bluewin dot ch Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.13 OS: Windows
Private report: No CVE-ID: None
 [2010-04-22 15:49 UTC] joel dot gaehwiler at bluewin dot ch
Description:
------------
We use this array:
array(2) { [1]=>  int(100) [2]=>  int(200) }

When a array will be encoded into a json string, php converts integer indexes t o strings:
string(17) "{"1":100,"2":200}"

When php decodes the json string back, it will be an object:
object(stdClass)#1 (2) { ["1"]=>  int(100) ["2"]=>  int(200) }

To avoid the problem that you not can acces integer indexes of a object you must cast the object to an array:
array(2) { ["1"]=>  int(100) ["2"]=>  int(200) }

Now the indexes become strings instead of integers, which you cannot access:
$arr2[1] = NULL


The json_decode function should convert indexes back to integer, if they are a string number, like php always does when you create an array.


Test script:
---------------
$arr = array(1=>100,2=>200,"1"=>100,"2"=>200);
$json = json_encode($arr);
$arr2 = (array)json_decode($json);
	
var_dump($arr2);
var_dump($arr2[1]);
var_dump($arr2["1"]);

Expected result:
----------------
array(4) {
  [1]=>
  int(100)
  [2]=>
  int(200)
}
int(100)
int(100)


Actual result:
--------------
array(4) {
  ["1"]=>
  int(100)
  ["2"]=>
  int(200)
}
NULL
NULL


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-04-22 17:28 UTC] johannes@php.net
-Status: Open +Status: Bogus
 [2010-04-22 17:28 UTC] johannes@php.net
This is expected, javaScript arrays are zero-indexed so your PHP array can't be represented as a javaScript array and has to be converted to an object. When converting an object back PHP defaults to objects. But you can use the second param for json_decode().

For the inaccessible keys which are the result then there's another report already. So that part is duplicate.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 28 22:01:28 2024 UTC