【问题标题】:Access to element with index ["0"] [duplicate]访问索引为 [“0”] 的元素 [重复]
【发布时间】:2013-08-11 17:37:27
【问题描述】:

请帮忙解决问题

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

)

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

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

但结果我得到了 NULL。

【问题讨论】:

  • $obj->{'0'}->value?

标签: php


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    $array = (array)$obj;
    var_dump($array[0]);
    

    【讨论】:

    • "...我尝试转换为数组:$array = (array)$obj; var_dump($array["0"]); 但结果我得到 NULL。" --OP
    • 你如何得到这个输出?
    • @brbcoding:试试json_decode('{"0":{"value":1}}')。将数组转换为对象并返回是正确的,因为 PHP 知道如何正确地做到这一点……但 json_decode 相当笨拙,并使用数字字符串(而不是整数)键创建对象。跨度>
    • @brbcoding:您错误地创建了初始状态。这就是它起作用的原因。
    • 啊,就是这样。我的错。
    猜你喜欢
    • 2013-10-13
    • 2016-04-02
    • 2011-02-24
    • 2022-01-18
    • 2020-02-18
    • 2017-04-23
    • 2016-07-14
    • 2017-05-21
    • 1970-01-01
    相关资源
    最近更新 更多