0

请帮忙解决问题

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

)

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

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

但结果我得到了NULL。

4

2 回答 2

2

转换为数组没有帮助。如果您尝试,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,因为他首先在评论中说对了!

于 2013-08-09T17:57:44.080 回答
0
$array = (array)$obj;
var_dump($array[0]);
于 2013-08-09T17:44:30.970 回答