dqmfo84644 2013-02-12 14:02
浏览 211
已采纳

在foreach内部循环,直到找到第一个匹配的元素

First of all apologies for the vague question title. I couldn't come up with a title that made sense.

I'm looping through image files in a directory using:

$folder = 'frames/*';
foreach(glob($folder) as $file)
{

}

The Requirement

I want to measure each file's size and if it's size is less then 8kb, move to the next file and check it's size and do so until you get the file whose size is greater than 8kb. Right now I'm using

$size = filesize($file);
if($size<8192) // less than 8kb file
{
    // this is where I need to keep moving until I find the first file that is greater than 8kb
   // then perform some actions with that file
}
// continue looping again to find another instance of file less than 8kb

I had a look at next() and current() but couldn't come up with a solution that I was looking for.

So for a result like this:

File 1=> 12kb
File 2=> 15kb
File 3=> 7kb // <-- Found a less than 8kb file, check next one
File 4=> 7kb // <-- Again a less than 8kb, check next one
File 5=> 7kb // <-- Damn! a less than 8kb again..move to next
File 6=> 13kb // <-- Aha! capture this file
File 7=> 12kb
File 8=> 14kb
File 9=> 7kb
File 10=> 7kb
File 11=> 17kb // <-- capture this file again
.
.
and so on

UPDATE

The complete code that I'm using

$folder = 'frames/*';
$prev = false;
foreach(glob($folder) as $file)
{
    $size = filesize($file);    
    if($size<=8192)
    {
       $prev = true;
    }

    if($size=>8192 && $prev == true)
    {
       $prev = false;
       echo $file.'<br />'; // wrong files being printed out    
    }
}
  • 写回答

1条回答 默认 最新

  • douye9175 2013-02-12 14:04
    关注

    What you need to do is keep a variable indicating if the previous analyzed file was a small one or a big one and react accordingly.

    Something like this :

    $folder = 'frames/*';
    $prevSmall = false; // use this to check if previous file was small
    foreach(glob($folder) as $file)
    {
        $size = filesize($file);
        if ($size <= 8192) {
            $prevSmall = true; // remember that this one was small
        }
    
        // if file is big enough AND previous was a small one we do something
        if($size>8192 && true == $prevSmall)
        {
            $prevSmall = false; // we handle a big one, we reset the variable
            // Do something with this file
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?