请帮助解决问题
stdClass Object
(
[0] => stdClass Object
(
[value] => 1
)
)
如何访问元素[0]?我尝试转换为数组:
$array = (array)$obj;
var_dump($array["0"]);
但结果我得到了NULL。
答案 0 :(得分:2)
转换为数组无济于事。如果你尝试,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因为他先在评论中说得对!
答案 1 :(得分:0)
$array = (array)$obj;
var_dump($array[0]);