Listing files in numerical order instead of alphab

2019-07-01 16:40发布

Basically, I have a bunch of files with a common prefix (logo%d.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 (Instead of logo20.jpg)

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

3条回答
Viruses.
2楼-- · 2019-07-01 17:26

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

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

Which gives (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.

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`

Which would generate

logo001.jpg

for decimal 1.

查看更多
手持菜刀,她持情操
3楼-- · 2019-07-01 17:27

Load into an array and use natsort()

查看更多
走好不送
4楼-- · 2019-07-01 17:38

If you're using ls like you say...

ls | sort -n

will do the trick.

查看更多
登录 后发表回答