PHP - 未定义的偏移量:0

Gra*_*avy 3 php arrays object

print_r($p->attachments) 生产:

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

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

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

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

我无法修改$ p对象.

编辑:

正如所建议的,这里是来自Var_dump的响应($ p->附件)

 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) {
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Suv*_*ker 12

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

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

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

$array = $array + array(null);
Run Code Online (Sandbox Code Playgroud)

因此,如果未设置原始$ array [0],则现在为null