请帮忙解决问题
stdClass Object
(
[0] => stdClass Object
(
[value] => 1
)
)
如何访问元素 [0]?我尝试转换为数组:
$array = (array)$obj;
var_dump($array["0"]);
但结果我得到了NULL。
请帮忙解决问题
stdClass Object
(
[0] => stdClass Object
(
[value] => 1
)
)
如何访问元素 [0]?我尝试转换为数组:
$array = (array)$obj;
var_dump($array["0"]);
但结果我得到了NULL。
转换为数组没有帮助。如果您尝试,PHP 有创建不可访问的数组元素的讨厌习惯:
一些测试代码:
$o = new stdClass();
$p = "0";
$o->$p = "foo";
print_r($o); // This will hide the true nature of the property name!
var_dump($o); // This reveals it!
$a = (array) $o;
var_dump($a); // Converting to an array also shows the string array index.
echo $a[$p]; // This will trigger a notice and output NULL. The string
// variable $p is converted to an INT
echo $o->{"0"}; // This works with the original object.
此脚本创建的输出:
stdClass Object
(
[0] => foo
)
class stdClass#1 (1) {
public $0 =>
string(3) "foo"
}
array(1) {
'0' =>
string(3) "foo"
}
Notice: Undefined index: 0 in ...
foo
赞美@MarcB,因为他首先在评论中说对了!
$array = (array)$obj;
var_dump($array[0]);