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

时间:2013-02-12 14:02:43

标签: php file foreach directory glob

首先为模糊的问题标题道歉。我无法想出一个有意义的标题。

我正在使用:

循环浏览目录中的图像文件
$folder = 'frames/*';
foreach(glob($folder) as $file)
{

}

要求

我想测量每个文件的大小,如果它的大小小于8kb,请移动到下一个文件并检查它的大小,直到得到大小大于8kb的文件为止。现在我正在使用

$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

我查看了next()current(),但无法找到我正在寻找的解决方案。

所以对于这样的结果:

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

更新

我正在使用的完整代码

$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 个答案:

答案 0 :(得分:2)

您需要做的是保留一个变量,指示先前分析的文件是小文件还是大文件,并做出相应的反应。

这样的事情:

$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
    }
}