繁体   English   中英

无法访问从json_decode创建的stdClass转换的数组中的元素

[英]Cannot access element in array converted from stdClass created by json_decode

$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";

var_dump($arr);

$arr = json_encode($arr);

$arr = (array)json_decode($arr);

var_dump($arr);

var_dump( $arr[1]);
var_dump( $arr["1"]);

如果我们删除第4行$ arr [“other_option”] =“2123”,则最后2个var_dump的输出为NULL NULL。 它会正确输出,但我不明白为什么!

而不是类型转换为数组,在json_encode设置为true

如果为TRUE,则返回的对象将转换为关联数组。

$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";
$arr = json_encode($arr);   
$arr = json_decode($arr,true);
var_dump( $arr['other_option']); // return 2123

working DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM