Bug #51635 [Opn->Bgs]: casting json objects to array
| From: | johannes@php.net | Date: | Thu, 22 Apr 2010 15:28:09 +0000 |
| Subject: | Bug #51635 [Opn->Bgs]: casting json objects to array | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-149790@lists.php.net to get a copy of this message | ||
Edit report at http://bugs.php.net/bug.php?id=51635&edit=1
ID: 51635
Updated by: johannes@php.net
Reported by: joel dot gaehwiler at bluewin dot ch
Summary: casting json objects to array
-Status: Open
+Status: Bogus
Type: Bug
Package: JSON related
Operating System: Windows
PHP Version: 5.2.13
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2010-04-22 15:49:33] 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
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/bug.php?id=51635&edit=1