Jasom Dotnet
Jasom Dotnet

Reputation: 1317

Decode json with dynamic line using PHP?

this is my code after json_decode:

stdClass Object (
    [batchcomplete] => 
    [query] => stdClass Object (
            [pages] => stdClass Object (
                    [56667] => stdClass Object (
                            [pageid] => 56667
                            [ns] => 0
                            [title] => Hanoi
                            [contentmodel] => wikitext
                            [pagelanguage] => en
                            [touched] => 2015-10-25T20:13:21Z
                            [lastrevid] => 687471695
                            [length] => 53648
                            [fullurl] => https://en.wikipedia.org/wiki/Hanoi
                            [editurl] => https://en.wikipedia.org/w/index.php?title=Hanoi&action=edit
                            [canonicalurl] => https://en.wikipedia.org/wiki/Hanoi
                        )
                )
        )
)

How I can get values [title], [fullurl] and [pageid] using PHP? I don't now how to go through line [56667] => stdClass Object ( because 56667 is dynamic (it depends on request).

Upvotes: 1

Views: 489

Answers (1)

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

You can use reset() to get the first array value. This will NOT require you to know the key.

Try this:

$output = json_decode($output, true); // convert to array so we can use reset.

$output_details = reset($output['query']['pages']);

$output_details['title']; // title
$output_details['fullurl']; // fullurl
$output_details['pageid']; // pageid

Upvotes: 3

Related Questions