How can I use PHP to get the nth element in a JSON object?

Well, that's why the daily twitter list is 20 trends. Let's say I want to get the 7th trend in the list. Here is my long way to do this ...

// We want the 7th item in the array
$trendArray = 7;

// Get an array (?) of the latest twitter trends
$jsonurl = "http://search.twitter.com/trends/daily.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
$allTrends = $json_output->trends;

// Cycle through to the 7th in the list
foreach ( $json_output->trends as $trendslist ) {
    foreach ( $trendslist as $trend ) {
            $loop += 1;
            if ($loop == $trendArray) {     
                $theTrend = $trend->name;
                break;  
            }
    }
    break; // Exit after we've looped once
}   

echo $theTrend;

I suspect I'm confusing objects and arrays, but I'm sure there is a much easier way to do this than with the two for each loop, because

$theTrend = $json_output->trends[6]->name;

Gives me this error:

Fatal error: Cannot use object of type stdClass as array 

Thank you for your help!

+3
source share
1 answer
$json_output = json_decode($json);

it should be:

$json_output = json_decode($json,true);

(You must tell json to convert stdClass to arrays)

EDIT: see http://php.net/manual/en/function.json-decode.php

+6
source

Source: https://habr.com/ru/post/1751587/


All Articles