Bug #70925 [Opn->Wfx]: json_decode-d object become inacccessible after converting to array
Edit report at https://bugs.php.net/bug.php?id=70925&edit=1
ID: 70925
Updated by: cmb@php.net
Reported by: speller at yandex dot ru
Summary: json_decode-d object become inacccessible after
converting to array
-Status: Open
+Status: Wont fix
Type: Bug
Package: Scripting Engine problem
PHP Version: 5.6.15
-Assigned To:
+Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
Won't fix according to bug #45959.
> The recommended solution is to use the second parameter of
> json_decode to have the son decoded as an array without the need
> to cast it.
Exactly.
Previous Comments:
------------------------------------------------------------------------
[2016-05-18 11:16:55] cmb@php.net
Related To: Bug #72232
------------------------------------------------------------------------
[2015-11-17 03:01:37] nhojohl at gmail dot com
This is a known issue and was marked as "won't fix" long ago. It's in the
official PHP documentation as well.
http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
"If an object is converted to an array, the result is an array whose elements are the
object's properties. The keys are the member variable names, with a few notable exceptions:
integer properties are unaccessible"
The recommended solution is to use the second parameter of json_decode to have the son decoded as an
array without the need to cast it.
For more information see: https://bugs.php.net/bug.php?id=45959
------------------------------------------------------------------------
[2015-11-17 02:36:45] speller at yandex dot ru
Description:
------------
Bug converting json_decoded-d object to array. First seen in PHP 5.4. Confirmed in PHP 5.6.15.
See the test script.
We have a simple array $a. Next we convert it to JSON and back. But after transcoding we can not
access the array's values and get NULL or "Notice: Undefined offset: 1".
If replace the line "$a = (array)json_decode(json_encode($a));" with "$a =
(array)((object)$a);" everything is OK, converted array's values are accessible.
The test script output is:
array(2) {
[1] =>
string(7) "value 1"
[2] =>
string(7) "value 2"
}
string(7) "value 1"
string(7) "value 1"
array(2) {
'1' =>
string(7) "value 1"
'2' =>
string(7) "value 2"
}
NULL
NULL
Test script:
---------------
<?
error_reporting(0);
$a = ['1' => 'value 1', '2' => 'value 2'];
var_dump($a);
var_dump($a[1]);
var_dump($a['1']);
$a = (array)json_decode(json_encode($a));
var_dump($a);
var_dump($a[1]);
var_dump($a['1']);
?>
Expected result:
----------------
The values of the converted array must be accessible
Actual result:
--------------
NULL or Notice: Undefined offset: 1
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=70925&edit=1
Thread (4 messages)