tags:

views:

40

answers:

1

Ok, so the twitter daily trends list is 20 trends long. Let's say I want to get the 7th trend on the list. Here's my longwinded way of doing it...

// 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 simpler way of doing this than with those two for/each loops because

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

Gives me this error:

Fatal error: Cannot use object of type stdClass as array 

Thanks for your help!

+5  A: 
$json_output = json_decode($json);

must be:

$json_output = json_decode($json,true);

(You have to tell json to convert the stdClass to arrays)

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

CuSS
To clarify: Once you add that second argument, you'll be able to use $theTrend = $json_output->trends[6]->name;
Ryan Kinal
@Richard ShepherdCan you mark as correct answer please?
CuSS
@Ryan KinalHe can convert the stdClass to array manualy (array)$json_output->trends[6], but this way is more simpler xD (sorry for my english)
CuSS
Thanks for you help - works perfect! :)
Richard Shepherd