title: How can I use PHP to get the nth item in a JSON object?
body: <p>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...</p>
  
  <pre><code>// 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-&gt;trends;
  
  // Cycle through to the 7th in the list
  foreach ( $json_output-&gt;trends as $trendslist ) {
      foreach ( $trendslist as $trend ) {
              $loop += 1;
              if ($loop == $trendArray) {     
                  $theTrend = $trend-&gt;name;
                  break;  
              }
      }
      break; // Exit after we've looped once
  }   
  
  echo $theTrend;
  </code></pre>
  
  <p>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 </p>
  
  <pre><code>$theTrend = $json_output-&gt;trends[6]-&gt;name;
  </code></pre>
  
  <p>Gives me this error:</p>
  
  <pre><code>Fatal error: Cannot use object of type stdClass as array 
  </code></pre>
  
  <p>Thanks for your help!</p>