如何在字符串数组包含int值时对其进行排序

时间:2018-01-25 11:36:37

标签: php arrays sorting

$files = array (
  '/test/tmp/file_7.sql.gz',
  '/test/tmp/file_9.sql.gz',
  '/test/tmp/file_11.sql.gz',
  '/test/tmp/file_1.sql.gz',
  '/test/tmp/file_3.sql.gz',
  '/test/tmp/file_12.sql.gz',
  '/test/tmp/file_13.sql.gz',
  '/test/tmp/file_10.sql.gz',
  '/test/tmp/file_5.sql.gz',
  '/test/tmp/file_2.sql.gz',
  '/test/tmp/file_8.sql',
  '/test/tmp/file_4.sql.gz',
  '/test/tmp/file_6.sql.gz',
);

echo "<pre>";
sort($files);
print_r($files);

使用sort()时,它会提供如下所示的输出

Array
(
    [0] => /test/tmp/file_1.sql.gz
    [1] => /test/tmp/file_10.sql.gz
    [2] => /test/tmp/file_11.sql.gz
    [3] => /test/tmp/file_12.sql.gz
    [4] => /test/tmp/file_13.sql.gz
    [5] => /test/tmp/file_2.sql.gz
    [6] => /test/tmp/file_3.sql.gz
    [7] => /test/tmp/file_4.sql.gz
    [8] => /test/tmp/file_5.sql.gz
    [9] => /test/tmp/file_6.sql.gz
    [10] => /test/tmp/file_7.sql.gz
    [11] => /test/tmp/file_8.sql
    [12] => /test/tmp/file_9.sql.gz
)

但我希望它像这样

Array
(
    [0] => /test/tmp/file_1.sql.gz
    [1] => /test/tmp/file_2.sql.gz
    [2] => /test/tmp/file_3.sql.gz
    [3] => /test/tmp/file_4.sql.gz
    [4] => /test/tmp/file_5.sql.gz
    [5] => /test/tmp/file_6.sql.gz
    [6] => /test/tmp/file_7.sql.gz
    [7] => /test/tmp/file_8.sql
    [8] => /test/tmp/file_9.sql.gz
    [9] => /test/tmp/file_10.sql.gz
    [10] => /test/tmp/file_11.sql.gz
    [11] => /test/tmp/file_12.sql.gz
    [12] => /test/tmp/file_13.sql.gz
)

2 个答案:

答案 0 :(得分:2)

您必须使用natural order算法:natsort()

natsort($files);

使用array_values()重置索引。例如:

natsort($files);
$files = array_values($files);
echo "<pre>";
print_r($files);

答案 1 :(得分:1)

您可以将natsort()array_values()

一起使用
echo "<pre>";
natsort($files);
$files= array_values($files);
print_r($files);
echo "</pre>";