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) {
}
}
}
最佳答案
您可以使用 isset() 来检查数组:
if(isset($p->attachments[0])){
echo $p->attachments[0]->url;
}
else {
//some error?
}
或者如果你知道你只会检查索引 0 那么你可以这样做
$array = $array + array(null);
所以如果原来的 $array[0] 没有设置,现在它是空的
关于PHP - undefined offset : 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18880448/