Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined index in multidimensional array

I'm using amazon products API.

$ItemAttr = $Item['ItemAttributes'];

Now $ItemAttr contains a multidimensional array.

if(is_array($ItemAttr["Author"])){$Author = implode(", ", $ItemAttr["Author"]);
}else{
$Author = $ItemAttr["Author"];}

Now when i use the above code i'm getting Undefined index: Author in line 1 and line 3

I tried like this

if(isset($ItemAttr["Author"])) {
if(is_array($ItemAttr["Author"])){$Author = implode(", ", $ItemAttr["Author"]);
}else{
$Author = $ItemAttr["Author"];}
}

It eliminates that error.

But later, When I use code like this $RetVal = array( 'Author' => $Author); i'm getting Undefined variable : Author error

Can anyone tell me the proper way?

Please note: $Item['ItemAttributes']; may or may no contain Author key. I mean if the returned product is a book, the array will return author key. Else it will not..

like image 897
Giri Avatar asked Mar 05 '26 21:03

Giri


1 Answers

Initialize the empty variable $Author on top?

$Author = ""; //initialize here

if(isset($ItemAttr["Author"])) 
{
    if(is_array($ItemAttr["Author"]))
    {
        $Author = implode(", ", $ItemAttr["Author"]);
    }
    else
    {
        $Author = $ItemAttr["Author"];
    }
}
like image 59
David Müller Avatar answered Mar 08 '26 13:03

David Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!