以数字顺序列出文件而不是字母顺序? [英] Listing files in numerical order instead of alphabetical?

查看:100
本文介绍了以数字顺序列出文件而不是字母顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一堆具有公共前缀的文件( logo%d.jpg )。

Basically, I have a bunch of files with a common prefix (logo%d.jpg) .

当使用 ls 查看它们时,甚至在循环遍历PHP中的目录时,我不会按数字顺序接收它们,这意味着 logo1.jpg ,logo2.jpg

When they are viewed using ls or even when looping through a directory in PHP, I don't receive them in numerical order, meaning logo1.jpg, logo2.jpg.

而是按字母顺序排列,如:

Instead I get them in alphabetical order, like:

logo1.jpg, logo10.jpg,logo11.jpg ... logo 19.jpg,logo2.jpg (而不是 logo20.jpg

有没有办法以数字顺序输出它们? logo1,logo2,logo3等。

Is there a way to ouput them in numerical order? logo1, logo2, logo3 .. etc.

推荐答案

他们在数组中,并使用 natsort ­ Docs 功能:

You could put them in an array and sort the array with the natsort­Docs function:

$array = array('logo1','logo2','logo12');
natsort($array);

哪个给了( Demo ):

array(3) {
  [0]=>
  string(5) "logo1"
  [1]=>
  string(5) "logo2"
  [2]=>
  string(6) "logo12"
}

寻找通常称为自然秩序。

The order you're looking for is often called natural order.

或者,您可以前缀数字,例如如果您已经在使用 sprintf 命名文件,以便标准排序订单仍然可以工作:

Alternatively, you could prefix the numbers, e.g. if you're already using sprintf to name the files, so that the standard sort order would still work:

`logo%03d.jpg`

哪些会生成

logo001.jpg

十进制 1

这篇关于以数字顺序列出文件而不是字母顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆