【问题标题】:Looping inside foreach till first matched element is found在 foreach 中循环直到找到第一个匹配的元素
【发布时间】:2013-02-12 14:02:43
【问题描述】:

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

我正在使用以下方式遍历目录中的图像文件:

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

【问题讨论】:

    标签: php file foreach directory glob


    【解决方案1】:

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

    类似这样的:

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

    【讨论】:

    • 这将对所有大于 8kb 的文件运行。我想要的是先找到一个小于 8kb 的文件,然后只捕获大于 8kb 的第一个文件而不是全部
    • 谢谢。让我看一遍,我会告诉你的。
    • 逻辑似乎是正确的,但我没有得到损坏的输出。让我看看我的文件是否有问题。
    • @asprin 如果它仍然不起作用,请尝试使用您的新代码更新您的问题,以便我查看它
    • @asprin 你不是用同样的大小来定义一个小文件和一个大文件,这正常吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多