访问索引为[“0”]的元素


Access to element with index ["0"]

请帮助解决问题

stdClass Object
(
    [0] => stdClass Object
        (
            [value] => 1
        )
)

如何访问元素[0]?我尝试转换为数组:

$array = (array)$obj;
var_dump($array["0"]);

但结果我得到了NULL。

转换为数组没有帮助。PHP有一个讨厌的习惯,如果你尝试,就会创建一个不可访问的数组元素:

  1. 对象属性名称始终是一个字符串,即使它是一个数字
  2. 将该对象转换为数组将保留所有属性名称作为新的数组键,这也适用于只有数字的字符串
  3. 尝试使用字符串"0"作为数组索引将被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]);