我想扫描目录并按升序将所有文件名添加到数组中(数字,无字母)。似乎正在发生的是scandir()
正在按第一个数字的最高值而不是整数进行排序。我需要考虑丢失的文本文件,因此如果缺少9.txt
,10.txt
将取代它(数组中没有空位)。
以下是代码:
<?php
$array=array();
$int = 1;
$holder=scandir("/postexamples/");
krsort($holder);
foreach($holder as $x)
{
if(!is_dir($x)){
$array[$int]=$x;
$int++;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
print_r($array);
?>
哪个输出数组:
Array ( [1] => 9.txt [2] => 8.txt [3] => 7.txt [4] => 6.txt [5] => 5.txt [6] => 4.txt [7] => 3.txt [8] => 20.txt [9] => 2.txt [10] => 19.txt [11] => 18.txt [12] => 17.txt [13] => 16.txt [14] => 15.txt [15] => 14.txt [16] => 13.txt [17] => 12.txt [18] => 11.txt [19] => 10.txt [20] => 1.txt )
有更好的(并且最好是有效的)方法吗?我需要它像[1] => 1.txt [2] => 2.txt
编辑:
我需要这个数组显示如下:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 17.txt [18] => 18.txt [19] => 19.txt [20] => 20.txt )
如果缺少一个文件(例如17.txt
),它将如下所示:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 18.txt [18] => 19.txt [19] => 20.txt )
答案 0 :(得分:1)
我是这样做的。
$files = array_diff(scandir("/postexamples/"), array('.', '..' ));
$array = array();
foreach($files as $file){
if(!is_dir($file)){
$array[]=$file;
}
}
sort($array, SORT_NUMERIC);
如果没有正确的数字,您可能必须使用usort。此外,如果您使用的是php&gt; = 5.4,则可以使用
scandir("/postexamples/", SCANDIR_SORT_ASCENDING );
但我没有尝试过。使用数字标记排序(不要忘记它只是一个像其他任何数组一样的数组)
$a = Array ( '9.txt', '8.txt', '7.txt', '6.txt', '10.txt', '1.txt');
echo "<pre>";
var_export($a);
echo "<br>";
sort($a, SORT_NUMERIC);
var_export($a);
结果
array (
0 => '9.txt',
1 => '8.txt',
2 => '7.txt',
3 => '6.txt',
4 => '10.txt',
5 => '1.txt',
)
array (
0 => '1.txt',
1 => '6.txt',
2 => '7.txt',
3 => '8.txt',
4 => '9.txt',
5 => '10.txt',
)
基本上sort($a, SORT_NUMERIC);
答案 1 :(得分:1)
您需要进行自然排序才能以正确的顺序获取文件(20.txt,10.txt,2.txt,1.txt)。执行此操作的功能是natsort。
$sortPath = 'postexamples/';
$files = array();
foreach (scandir($sortPath) as $file) {
if (is_file("$sortPath/$file")) {
$files[] = $file;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
natsort($files);
$files = array_values($files); // re-key array
print_r($files);
Final array:
Array
(
[0] => 1.txt
[1] => 2.txt
[2] => 4.txt
[3] => 10.txt
[4] => 20.txt
)
答案 2 :(得分:0)
试试这个,我希望这会对你有所帮助:
$ar=array();
$g=scandir("/postexamples/");
krsort($g)
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else $ar[]=$x;
}
print_r(sort($ar));