PHP - 未定义的偏移量:0

5

print_r($p->attachments) 的输出结果如下:

Array
(
    [0] => stdClass Object
        (
            [id] => ...
            [url] => http://...png
            [slug] => ...
            [title] => ...
            [description] => ...
            [caption] => ...
            [parent] => ...
            [mime_type] => image/png
            [images] => ...
                (
                )
        )
)

我希望能访问“url”字段中的值。
使用print_r($p->attachments[0]->url)可以检索到url,但也会产生:Undefined offset: 0
现在,我可以通过调用print_r(@$p->attachments[0]->url)来抑制错误,但有没有适当的方法来解决这个问题?
我不能修改$p对象。
编辑:
如建议所示,以下是Var_dump($p->attachments)的响应。
 array(1) {
  [0]=>
  object(stdClass)#322 (9) {
    ["id"]=>
    int(1814)
    ["url"]=>
    string(76) "..."
    ["slug"]=>
    string(34) "..."
    ["title"]=>
    string(34) "..."
    ["description"]=>
    string(0) ""
    ["caption"]=>
    string(53) "..."
    ["parent"]=>
    int(1811)
    ["mime_type"]=>
    string(9) "image/png"
    ["images"]=>
    array(0) {
    }
  }
}

1
尝试使用var_dump()函数来输出对象 -- 值可能没有被设置。 - Sterling Archer
5
@DontVoteMeDown 如果我能的话,我愿意这么做。但是这样只是掩盖问题而不是解决问题。 - George Brighton
4
每次尝试访问$p->attachments[0]时似乎未定义。您可以通过在尝试访问之前使用if(isset($p->attachments[0])) { .... }来抑制错误。 - steven
从您提供的代码来看,没有出现错误的原因。我猜 $p->attachments 有时为空,这种情况下在访问其第一个元素之前需要进行检查。 - George Brighton
@GeorgeBrighton array_key_exists,如果希望在映射中有一个null值怎么办?允许在映射中保留NULL值是一种非常常见的结构。不过,考虑到这个新知识,我认为大多数情况下,使用isset是最好的选择。 - crush
显示剩余10条评论
2个回答

15
您可以使用isset()来检查数组:
if(isset($p->attachments[0])){
    echo $p->attachments[0]->url;
}
else {
  //some error?
}

或者,如果您知道只需要检查索引0,则可以这样做

$array = $array + array(null);

所以如果原始的 $array[0] 被取消设置,现在它就是 null


0

不知道为什么它会返回一个值并告诉你有未定义的偏移量0。很奇怪。

你能检查一下吗(因为附件是一个数组,所以你应该这样做):

if ( count($p->attachments) > 0 ){ 
   foreach ($p->attachments AS $att){
    //do the stuff if attachement 
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接