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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?