Is there any way for natsort()
to also change the indexes?
I.e.
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
natsort($array);
Array
(
[0] => IMG0.png
[4] => img1.png
[3] => img2.png
[5] => IMG3.png
[2] => img10.png
[1] => img12.png
)
But I want:
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
natsort($array);
Array
(
[0] => IMG0.png
[1] => img1.png
[2] => img2.png
[3] =&开发者_StackOverflow社区gt; IMG3.png
[4] => img10.png
[5] => img12.png
)
array_values
will effectively reindex any array passed to it with sequential integer keys. So you just need to do:
natsort($array);
$array = array_values($array);
Just use array_values
to get the values of the array and break the key-value association:
<?php
$tarray = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
natsort($tarray);
$tarray = array_values($tarray);
?>
So:
<?php
$tarray = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
print_r($tarray);
natsort($tarray);
$tarray = array_values($tarray);
print_r($tarray);
?>
yields:
Array
(
[0] => IMG0.png
[1] => img12.png
[2] => img10.png
[3] => img2.png
[4] => img1.png
[5] => IMG3.png
)
Array
(
[0] => IMG0.png
[1] => IMG3.png
[2] => img1.png
[3] => img2.png
[4] => img10.png
[5] => img12.png
)
See comment on natsort.
Simply use sort()
with its natural sorting flag. This way you don't need to bother calling array_values()
to re-index.
Code: (Demo)
sort($array, SORT_NATURAL);
var_export($array);
精彩评论