如何从目录回显前N个文件

对于平面文件新闻发布者,我将所有数据存储在.txt文件中 所有.txt文件的列表位于目录messages中 要获取新闻消息的所有标题(每个txt文件的第二行),请使用foreach:

foreach($pagenewsmsgs as $file){
    // open and prepare newsmessage
    $newsmsg = 'messages/';
    $newsmsg .= $file;
    $fh = fopen($newsmsg,'r');
    $txtnewsmsg1 = file_get_contents($newsmsg);
    $txtnewsmsg = stripslashes($txtnewsmsg1);                                               
    // get data out of txt file                             
    $lines = file($newsmsg,FILE_IGNORE_NEW_LInes);// filedata into an array                                                
    $news_title = $lines[1]; //  news title                                                             
    echo $news_title.'<br />'; // echo all the title from each .txt file

    fclose($fh);

} // end foreach

此循环使我回信了所有.txt文件的标题。 我该如何仅回响前5个.txt文件的标题?

wuhao1972 回答:如何从目录回显前N个文件

也许使用带有length参数的array_slice来选择所需的元素子集:

foreach(array_slice($pagenewsmsgs,5) as $file){
    [...]
}
,

设置一个计数器,并在达到五点时退出循环:

$counter = 0;
foreach($pagenewsmsgs as $file) {
    // do stuff
    $counter++;
    if(5 == $counter) {
        break;
    }
}
本文链接:https://www.f2er.com/3142129.html

大家都在问