限制要处理的JSON对象的数量[关闭]

<?php
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';

$username = 'username';  // authentication
$password = 'password';  // authentication

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password   // authentication
);

// Setting curl options
curl_setopt_array( $ch, $options );

// Getting results
$result =  curl_exec($ch); // Getting JSON result string

    $i=0;
    foreach (json_decode($result) as $obj) {
    if($i==5) break;
        $feedbin_title = $obj->title;
        $feedbin_url = $obj->url;
        echo '<li><a href="', $feedbin_url, '">', $feedbin_title, '</a></li>';
    }
?>

I get a 100 objects JSON result. I'm trying to limit the objects processed to the first 5. Why doesn't work the $i=0; if($i==5) break; thing? :)

A neater solution would be to use:

foreach (array_slice(json_decode($result), 0, 5) as $obj) {

It'll save you creating a variable just to count :)

You forgot to increment $i. Now it runs through the whole array, checking every time if $i, which is always 0, is equal to five.

Write instead:

if($i++ == 5) break;

which counts up until $i is 5.

You're not changing the $i value, try adding $i++ in your foreach() loop... try foreach(json_decode($result) as $i => $obj)