从foreach php中的数百个数据中只获取25个数据

时间:2013-07-06 06:42:29

标签: php foreach

我从xml中获取数据,其中有100个元素,我的代码:

foreach($sections->children() as $question){
    $xml_data .= 'Section Name: '.$question->section_name.'<br/>';
    $xml_data .= 'Question No.: '.$question->qno.'<br/>';
    if($question->answer == null || $question->answer == ''){
        $question->answer = 'Not attempted';
        $xml_data .= 'Answer: '.$question->answer.'<br/>';
    } else {
        $xml_data .= 'Answer: '.$question->answer.'<br/>';
    }
    $xml_data .= 'Time: '.$question->time.'<br/>';
    if($question->seen == '1'){
        $xml_data .= 'Seen<br/>';
    } else {
        $xml_data .= 'Not Seen<br/>';
    }
    if($question->flag == '1'){
        $xml_data .= 'Flaged<br/>';
    } else {
        $xml_data .= 'Not Flaged<br/>';
    }
}

从上面我得到了100个问题,但我只能从上面显示25个,我该怎么做?

2 个答案:

答案 0 :(得分:1)

$count = 1;
foreach($sections->children() as $question){

    ...
    ...

    if($count++ == 25){
        break;
    }
}

答案 1 :(得分:0)

这样做:

$t = 1; $rate=array(1 , 2 ,3 ,4 ,5 ); print_r($rate); foreach($rate as $rt){ echo $rt; if($rt==3){ exit;} $t++; }