PHP - 未定义的偏移量:0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18880448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:23:04  来源:igfitidea点击:

PHP - undefined offset: 0

phparraysobject

提问by Gravy

print_r($p->attachments)produces:

print_r($p->attachments)产生:

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

I wish to access the value in the urlfield

我希望访问该url字段中的值

print_r($p->attachments[0]->url)retrieves the url, but also produces: Undefined offset: 0

print_r($p->attachments[0]->url)检索网址,但也会产生: Undefined offset: 0

Now I can supress the error by calling print_r(@$p->attachments[0]->url), but is there a proper way of fixing this?

现在我可以通过调用来抑制错误print_r(@$p->attachments[0]->url),但是有没有正确的方法来解决这个问题?

I am not able to modify the $p object.

我无法修改 $p 对象。

Edit:

编辑:

As suggested, here is response from Var_dump($p->attachments)

正如所建议的,这是来自 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) {
    }
  }
}

回答by Suvash sarker

You can use isset() for check the array:

您可以使用 isset() 检查数组:

if(isset($p->attachments[0])){
    echo $p->attachments[0]->url;
}
else {
  //some error?
}

Or if you know that you are only going to be checking index 0 then you can do this way

或者,如果您知道您只会检查索引 0,那么您可以这样做

$array = $array + array(null);

So if the original $array[0] was unset, now it is null

所以如果原来的 $array[0] 没有设置,现在它是空的

回答by halfik

dunno why it returns you a value and informs you that there is undefined offset 0. strange.

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

can you check this (since attachments is an array you should do this that way):

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

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