PHP - 未定义的偏移量:0

时间:2013-09-18 19:12:49

标签: 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] => ...
                (
                )
        )
)

我希望访问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) {
    }
  }
}

2 个答案:

答案 0 :(得分:11)

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

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

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

$array = $array + array(null);

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

答案 1 :(得分:0)

不知道为什么它会返回一个值,并通知你存在未定义的偏移0.奇怪。

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

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