php glob() — 按名称排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7708387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
glob() — Sort by Name
提问by FrozenTime
How can I reverse the sort by filename? Currently it displays all the text files in alphabetical / numerical order, but I'm trying to have it display in descending order instead. Right now, I have...
如何按文件名反转排序?目前它以字母/数字顺序显示所有文本文件,但我试图让它以降序显示。目前,我有...
<?php
foreach (glob("*.txt") as $filename) {
include($filename);
}
?>
I'm pretty new to PHP, but I tried usort with array added on but that just resulted in it displaying only 1 of the text files, so either that doesn't work or I just coded it wrong.
我对 PHP 很陌生,但我尝试添加了数组的 usort 但这只是导致它只显示 1 个文本文件,所以要么不起作用,要么我只是编码错误。
回答by Foo Bah
You can use array_reverse
:
您可以使用array_reverse
:
foreach(array_reverse(glob("*.txt")) as $filename) { ...
回答by Gabriel Glenn
Just a addition to @Foo Bah's answer :
When dealing with file names in a directory, I usually add natsort
to prevent the typical ordering case :
只是对@Foo Bah 的回答的补充:在处理目录中的文件名时,我通常添加natsort
以防止出现典型的排序情况:
- 'image1.png'
- 'image10.png'
- 'image2.png'
- 'image1.png'
- 'image10.png'
- 'image2.png'
natsortis a more user friendly sorting algorithm that will preserve natural numbering :
natsort是一种更加用户友好的排序算法,它将保留自然编号:
- 'image1.png'
- 'image2.png'
- 'image10.png'
- 'image1.png'
- 'image2.png'
- 'image10.png'
So FooBah's answer becomes :
所以 FooBah 的答案变成了:
$list = glob("*.jpg");
natsort($list);
foreach(array_reverse($list) as $filename) { ...
Please note that natsort
is modifying the array passed in parameter and only returns a boolean.
请注意,这natsort
是修改传入参数的数组,并且只返回一个布尔值。
回答by alex
回答by Cédric Fran?oys
As the glob()
function sorts the filenames as default behaviour, you can simply loop through the resulting array in reverse order and therefore avoid any additional processing:
由于该glob()
函数将文件名排序为默认行为,您可以简单地以相反的顺序循环遍历结果数组,从而避免任何额外的处理:
<?php
for($result = glob("*.txt"), $i = count($result); $i > 0; --$i) {
include($result[$i-1]);
}
?>