PHP扫描目录和数组
我有一个脚本,它扫描一个文件夹,并将其中包含的文件名放入一个数组中。 然后我洗牌数组并显示文件名 像这样:PHP扫描目录和数组,php,arrays,directory,Php,Arrays,Directory,我有一个脚本,它扫描一个文件夹,并将其中包含的文件名放入一个数组中。 然后我洗牌数组并显示文件名 像这样: $count=0; $ar=array(); $i=1; $g=scandir('./images/'); foreach($g as $x) { if(is_dir($x))$ar[$x]=scandir($x); else { $count++; $ar[]=$x; } } shuffle($ar); whi
$count=0;
$ar=array();
$i=1;
$g=scandir('./images/');
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else
{
$count++;
$ar[]=$x;
}
}
shuffle($ar);
while($i <= $count)
{
echo $ar[$i-1];
$i++;
}
?>
$count=0;
$ar=array();
$i=1;
$g=scandir('./图像/');
外汇($g为$x)
{
如果(is_dir($x))$ar[$x]=scandir($x);
其他的
{
$count++;
$ar[]=$x;
}
}
洗牌($ar);
而我
它工作得很好,但出于某种原因,我得到了如下结果:
- fff.jpg
- ccc.jpg
- 排列
- nnn.jpg
- ttt.jpg
- sss.jpg
- bbb.jpg
- 排列
- eee.jpg
感谢您仅解释一下它为您提供
数组的部分
首先,返回以下内容:
从目录中返回文件和目录的数组
根据该返回值,它返回以下内容(这是一个示例,供参考):
这些点实际上是文件夹。现在在您的代码逻辑中,当它点击/迭代此点时:
if(is_dir($x))$ar[$x]=scandir($x); // if its a directory
// invoke another set of scandir into this directory, then append it into the array
这就是为什么结果数组有混合字符串,而另一个额外的/不需要的scandir
数组从返回值。
为了避免这些问题,可以使用肮脏的快速修复方法。只需跳过点:
foreach($g as $x)
{
// skip the dots
if(in_array($x, array('..', '.'))) continue;
if(is_dir($x))$ar[$x]=scandir($x);
else
{
$count++;
$ar[]=$x;
}
}
另一种选择是使用DirectoryIterator
:
$path = './images/';
$files = new DirectoryIterator($path);
$ar = array();
foreach($files as $file) {
if(!$file->isDot()) {
// if its not a directory
$ar[] = $file->getFilename();
}
}
echo '<pre>', print_r($ar, 1);
$path='./images/;
$files=新的DirectoryIterator($path);
$ar=array();
foreach($files作为$file){
如果(!$file->isDot()){
//如果不是目录
$ar[]=$file->getFilename();
}
}
回音“”,打印($ar,1);
更重要fun@Dagon我想那应该是鱼:)你是说地球仪吗?我去找地球仪,谢谢。同时,我想知道这个脚本(第一个)到底出了什么问题。在我的示例中,我只是“回显”文件名以使其变得简单,但我需要的不仅仅是这些。因此,我需要将这些名称存储在一个数组中,以供以后使用。我相信,不管是否是glob,我最终会遇到完全相同的问题。如果您需要递归搜索目录,您可以使用SPL库,因为@Baylock是否只包含图像,或者它是否也包含子文件夹?您是否也需要查看其子文件夹中的图像?非常感谢。就这样。其他投稿人的建议可能是正确的,但我需要知道这里发生了什么,你的回答完全有道理。@Baylock当然很高兴这一点light@l“L'L yes当然glob
会很酷而且很灵活,因为它甚至支持通配符和其他东西,当然没什么害处。@Ghost:-如果你觉得有帮助的话,可以把它添加到你的答案中,干杯:)不要欺骗自己;给自己更多的信任。我认为你给了他们一个很好的解释;-)
$path = './images/';
$files = new DirectoryIterator($path);
$ar = array();
foreach($files as $file) {
if(!$file->isDot()) {
// if its not a directory
$ar[] = $file->getFilename();
}
}
echo '<pre>', print_r($ar, 1);