I implemented the amazon books api just last month and i remember this exact same problem. How lucky are you as i never had me to help :(
Amazon is very annoying because there is no consistency within their returned structure (well, except for what's below, but that makes it annoying to consume):
- if one item is returned, it's an OBJECT
- if multiple items are returned, it's an ARRAY
- if nothing is returned, NOTHING exists at all
Personally i think they should have used empty arrays at least, and stick to arrays. You can always add objects to arrays >< but at least the structure would be consistant.
The way i got around it, was to create a new representation of the returned structure which GUARANTEED that everything was an array and that the WHOLE STRUCTURE was pre-defined. This way i could later access the data knowing 100% that it won't give me errors like it doesn't exist or is being accessed as an object when it is an array.
First, create the structure how you want it to be such as:
$structure = array(
'isbn' => '',
'authors' => array(),
'pictures' => array(),
'title' => ''
);
Then create a function or object method (depending on your style) to consume the amazon data returned and find what it can and insert it into your custom structure.
Remember to check that first it exists, and then if it is an array or an object so you know how to access it. It helps to print out a few returned results from amazon with a few different books.
Then, to access details about the book, you can rely on the data in the $structure ;) everything is an array, and everything is guaranteed to exist so doing:
foreach ($structure['authors']...
Won't produce an error that its not an array, doesn't exist or is in fact an object!!!
The sort of pseudo code would be:
$returned_amazon_data = get_amazon_data('http://amazon.com/api/book=1234567');
$book = consume_amazon_result($returned_amazon_data);
if ($book) {
//print out the authors, if no authors were found, will just stay blank as it's GUARANTEED to always be an array of strings
print implode($book['authors']);
}
Have fun! I know i did(nt)...