PHP - undefined offset : 0

标签 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) 检索 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/

相关文章:

php - 从 PHP Json 对象填充 JQuery 数据表

php - chown 在脚本中

javascript - 比较两个对象数组,如果不存在则推送

具有嵌套属性的 Javascript 合并对象

javascript - jquery中如何将数组json数据转换为特定的json?

php - foreach在mysql查询后没有为变量赋值

javascript - 如何循环遍历嵌套数组并为每个级别插入 id 和parentId?

c - uint 结构数组上的 async_work_group_copy

c++ - 如果 C++ 在 if 语句中创建对象时出现范围问题

php - 整个站点的单一类别表或不同用例的不同表