undefined offset php,PHP - undefined offset: 0

问题

print_r($p->attachments) produces:

Array

(

[0] => stdClass Object

(

[id] => ...

[url] => http://...png

[slug] => ...

[title] => ...

[description] => ...

[caption] => ...

[parent] => ...

[mime_type] => image/png

[images] => ...

(

)

)

)

I wish to access the value in the url field

print_r($p->attachments[0]->url) retrieves the url, but also produces: Undefined offset: 0

Now I can supress the error by calling print_r(@$p->attachments[0]->url), but is there a proper way of fixing this?

I am not able to modify the $p object.

Edit:

As suggested, here is response from 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) {

}

}

}

回答1:

You can use isset() for check the array:

if(isset($p->attachments[0])){

echo $p->attachments[0]->url;

}

else {

//some error?

}

Or if you know that you are only going to be checking index 0 then you can do this way

$array = $array + array(null);

So if the original $array[0] was unset, now it is null

回答2:

dunno why it returns you a value and informs you that there is undefined offset 0. strange.

can you check this (since attachments is an array you should do this that way):

if ( count($p->attachments) > 0 ){

foreach ($p->attachments AS $att){

//do the stuff if attachement

}

}

来源:https://stackoverflow.com/questions/18880448/php-undefined-offset-0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值