Pergunta

I've found similar questions, but none quite match my structure. I've never worked with JSON so I'm unclear how parsing it works.

All I am trying to do is echo out a JSON response from a url, and manipulate the response as variables. The structure is:

{"results":{"books":{"2014-05-13":[{"book":{"book_date":"2014-05-13","book_publisher":"Some Publisher","book_id":"123","book_author":"Some Author" etc etc etc

I'd like to be able to echo out and store each books date, publisher, id, author, into variables.

What I've been using causes the error: Invalid argument supplied for foreach()

$api_url = 'myurl/books.json';
$json = file_get_contents($api_url);
$json2 = json_decode($json, true);

foreach($json2->book as $book)
{
    echo $book->date;
    echo $book->publisher;
    echo $book->id;
    echo $book->date;
    echo $book->author;
}
Foi útil?

Solução

$json2 = json_decode($json,true);

will create an associative array

So you cant iterate it as object the way you are doing now.

You should get an array something as below

[results] => Array
        (
            [books] => Array
                (
                    [2014-05-13] => Array
                        (
                            [0] => Array
                                (
                                    [book] => Array
                                        (
                                            [book_date] => 2014-05-13
                                            [book_publisher] => Some Publisher
                                            [book_id] => 123
                                            [book_author] => Some Author
                                        )

                                )

                        )

                )

        )

)

So you need to use array index to loop through the data.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top