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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: joel dot gaehwiler at bluewin dot ch
New email:
PHP Version: OS:

 

 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2019 The PHP Group
All rights reserved.
Last updated: Tue Nov 19 00:01:39 2019 UTC