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) {
}
}
}
$p->attachments[0]
时似乎未定义。您可以通过在尝试访问之前使用if(isset($p->attachments[0])) { .... }
来抑制错误。 - steven$p->attachments
有时为空,这种情况下在访问其第一个元素之前需要进行检查。 - George Brightonarray_key_exists
,如果希望在映射中有一个null
值怎么办?允许在映射中保留NULL
值是一种非常常见的结构。不过,考虑到这个新知识,我认为大多数情况下,使用isset
是最好的选择。 - crush