【问题标题】:how to echo the first N files from a directory如何回显目录中的前 N ​​个文件
【发布时间】:2019-11-07 19:21:49
【问题描述】:

对于平面文件新闻列表,我将所有数据存储在 .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 文件的标题?

【问题讨论】:

  • 设置一个计数器并在达到 5 时退出循环。

标签: php arrays foreach


【解决方案1】:

也许使用array_slicelength 参数来选择您想要的元素子集:

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

【讨论】:

    【解决方案2】:

    设置一个计数器,当它达到 5 时退出循环:

    $counter = 0;
    foreach($pagenewsmsgs as $file) {
        // do stuff
        $counter++;
        if(5 == $counter) {
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多