PHP 扫描目录和数组
PHP scan directory and array
我有一个扫描文件夹并将其包含的文件名放入数组的脚本。
然后我打乱数组并显示文件名。
像这样:
$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++;
}
?>
效果很好,但出于某种原因,我得到了这样的结果:
- fff.jpg
- ccc.jpg
- 数组
- nnn.jpg
- ttt.jpg
- sss.jpg
- bbb.jpg
- 数组
- eee.jpg
当然,由于随机播放,刷新页面时顺序会发生变化,但在 200 个文件名中,我总是在列表的某处找到这 2 个 "Array"。
会是什么?
谢谢
只是为了解释它给你的部分Array
。
首先,scandir
return如下:
Returns an array of files and directories from the directory.
根据 return 值,它 return 编辑了这个(这是一个例子,供参考):
Array
(
[0] => . // current directory
[1] => .. // parent directory
[2] => imgo.jpg
[3] => logo.png
[4] => picture1.png
[5] => picture2.png
[6] => picture3.png
[7] => picture4.png
)
右边的那些点实际上是文件夹。现在在你的代码逻辑中,当它 hits/iterate 这个地方:
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
这就是为什么你的结果数组有混合字符串,而另一个 extra/unneeded scandir
数组 return 值来自 ..
可以使用肮脏的快速修复来避免这些问题。跳过点:
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);
我有一个扫描文件夹并将其包含的文件名放入数组的脚本。 然后我打乱数组并显示文件名。
像这样:
$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++;
}
?>
效果很好,但出于某种原因,我得到了这样的结果:
- fff.jpg
- ccc.jpg
- 数组
- nnn.jpg
- ttt.jpg
- sss.jpg
- bbb.jpg
- 数组
- eee.jpg
当然,由于随机播放,刷新页面时顺序会发生变化,但在 200 个文件名中,我总是在列表的某处找到这 2 个 "Array"。
会是什么?
谢谢
只是为了解释它给你的部分Array
。
首先,scandir
return如下:
Returns an array of files and directories from the directory.
根据 return 值,它 return 编辑了这个(这是一个例子,供参考):
Array
(
[0] => . // current directory
[1] => .. // parent directory
[2] => imgo.jpg
[3] => logo.png
[4] => picture1.png
[5] => picture2.png
[6] => picture3.png
[7] => picture4.png
)
右边的那些点实际上是文件夹。现在在你的代码逻辑中,当它 hits/iterate 这个地方:
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
这就是为什么你的结果数组有混合字符串,而另一个 extra/unneeded scandir
数组 return 值来自 ..
可以使用肮脏的快速修复来避免这些问题。跳过点:
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);