dqmfo84644 2013-02-12 06:02
浏览 212
已采纳

在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 06: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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部