我有这个文件路径/ 0 .php路径/ 3 .php路径/ 2 .php路径/ 7 < /强> .PHP
我想用foreach显示文件,我使用这段代码:
$files = glob("system/$var/$var/$var/*/*.php");
foreach($files as $file) {
//code here per $file.
//for example:
$basename = basename($file);
echo str_replace(".php",null,$basename) . "<br>";
include $file; //heres i need the path of the files.
}
但我想按.php扩展名之前的最大数字对这些文件进行排序,如下所示:
Array
(
[0] => path/7.php
[1] => path/3.php
[2] => path/2.php
[3] => path/0.php
)
所以?
更新,rsort对我不好,因为这是一个路径/到/文件,在数字之前,我想使用文件的路径。
答案 0 :(得分:2)
$files = glob("system/$var/$var/$var/*/*.php");
//Put each file name into an array called $filenames
foreach($files as $i => $file) $filenames[$i] = basename($file);
//Sort $filenames
rsort($filenames);
//Check output
print_r($filenames);
这将输出:
Array
(
[0] => 7.php
[1] => 3.php
[2] => 2.php
[3] => 0.php
)
要保留完整路径,可以使用路径作为键,使用基本名称作为值:
#For testing:
#$files = array("path/3.php", "path/1.php", "path/5.php", "path/7.php", "path/0.php");
//Put each path AND basename into an array called $filenames
foreach($files as $file) $filenames[basename($file)] = $file;
//Sort $filenames by basename with arsort()
arsort($filenames);
//Check output (listing the paths)
foreach($filenames as $k => $v) echo $v.PHP_EOL;
//Just the values
$filenames_with_paths = array_values($filenames);
print_r($filenames_with_paths);
这将输出:
path/7.php
path/5.php
path/3.php
path/1.php
path/0.php
Array
(
[0] => path/7.php
[1] => path/5.php
[2] => path/3.php
[3] => path/1.php
[4] => path/0.php
)
答案 1 :(得分:1)
您可以使用usort对所返回的数组进行排序:
$files = glob("system/$var/$var/$var/*/*.php"
usort($files, function ($b, $a) {
return strcmp( substr($a, strrpos($a, '/') + 1),
substr($b, strrpos($b, '/') + 1) );
});
请注意,这将使用字符串比较,因此10.php将在1.php和2.php之间结束。如果那不是你想要的,你必须使用数字比较。即使用PHP 7的“宇宙飞船”运营商:
$files = glob("system/$var/$var/$var/*/*.php"
usort($files, function ($b, $a) {
return ((int)substr($a, strrpos($a, '/') + 1))
<=> ((int)substr($b, strrpos($b, '/') + 1));
});
编辑:我在回调签名中交换$ a和$ b来反转排序顺序
答案 2 :(得分:0)
使用您的代码:
foreach(array_reverse($files) as $filename){}
答案 3 :(得分:0)
$files = glob("system/$var/$var/$var/*/*.php");
rsort($files);
foreach($files as $key){
echo $key;
}