0

在 $json_dailymile 中有 20 个条目。如何修改 foreach 以仅处理第一个(最新的) - 比如 - 5?

<?php
$json_dailymile = "http://api.dailymile.com/people/justfinish/entries.json";
$data_dailymile = json_decode(file_get_contents($json_dailymile), true);

$data_dailymile = $data_dailymile['entries'];

foreach ($data_dailymile as $run) {
    BLAHBLAH
}
?>
4

2 回答 2

2

添加一个在循环中每次递增的“哨兵”。一旦达到最大值,请打破循环:

<?php
$json_dailymile = "http://api.dailymile.com/people/justfinish/entries.json";
$data_dailymile = json_decode(file_get_contents($json_dailymile), true);

$data_dailymile = $data_dailymile['entries'];

$count = 0;
foreach ($data_dailymile as $run) {
    if($count > 5) break;
     //Code....
    $count++;
}
?>
于 2013-06-03T21:46:39.140 回答
1

在循环中使用计数器

$i=0;

foreach ($data_dailymile as $run) {
if($i==5) break;   
//BLAHBLAH goes here
$i++;
}
于 2013-06-03T21:46:58.210 回答