Php 在foreach内部循环,直到找到第一个匹配的元素
首先,我为这个模糊的问题标题道歉。我想不出一个有意义的标题 我正在使用以下命令循环浏览目录中的图像文件:Php 在foreach内部循环,直到找到第一个匹配的元素,php,file,foreach,directory,glob,Php,File,Foreach,Directory,Glob,首先,我为这个模糊的问题标题道歉。我想不出一个有意义的标题 我正在使用以下命令循环浏览目录中的图像文件: $folder = 'frames/*'; foreach(glob($folder) as $file) { } 要求 我想测量每个文件的大小,如果它的大小小于8kb,请移动到下一个文件并检查它的大小,直到得到大小大于8kb的文件为止。现在我正在使用 $size = filesize($file); if($size<8192) // less than 8kb file {
$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
$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
}
}
更新
我正在使用的完整代码
$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
$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
}
}
$folder='frames/*';
$prev=假;
foreach(全局($folder)作为$file)
{
$size=filesize($file);
如果($size8192&&$prev==true)
{
$prev=假;
echo$file.“
”;//打印错误的文件
}
}
您需要做的是保留一个变量,指示先前分析的文件是小文件还是大文件,并做出相应的反应
大概是这样的:
$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
}
}
$folder='frames/*';
$prevsall=false;//使用此选项检查上一个文件是否很小
foreach(全局($folder)作为$file)
{
$size=filesize($file);
如果($size 8192&&true==$prevsall)
{
$prevsall=false;//我们处理一个大的,我们重置变量
//对这个文件做些什么
}
}
这将对大于8kb的所有文件运行。我想要的是先找到一个小于8kb的文件,然后只捕获第一个大于8kb的文件,而不是全部谢谢。让我看一下,我会让你知道的。逻辑似乎是正确的,但我没有得到损坏的输出。让我看看我的文件中是否有任何错误。@asprin如果仍然无效,请尝试使用新代码更新您的问题,以便我可以查看it@asprin您没有使用相同的大小来定义一个小文件和一个大文件,这正常吗?