Arm Dubhe Arm Dubhe - 7 months ago 13
PHP Question

Is there any function to sort an array keys based in the consecutive number/ itself in php?

I'm tried many sorting functions in order to have an specific key order in a php array, this is my current array:

Array(
[1] => 1.txt
[21] => 2-1.txt
[221] => 2-2-1.txt
[22] => 2-2.txt
[231] => 2-3-1.txt
[2321] => 2-3-2-1.txt
[232] => 2-3-2.txt
[23] => 2-3.txt
[2] => 2.txt
)


I'm looking for something like this:

Array(
[1] => 1.txt
[2] => 2.txt
[21] => 2-1.txt
[22] => 2-2.txt
[221] => 2-2-1.txt
[23] => 2-3.txt
[231] => 2-3-1.txt
[232] => 2-3-2.txt
[2321] => 2-3-2-1.txt
)


Does somebody can give me a hand?

Answer

You can use uksort with strcmp on keys:

uksort( $array, 'strcmp' );

Result:

Array
(
    [1] => 1.txt
    [2] => 2.txt
    [21] => 2-1.txt
    [22] => 2-2.txt
    [221] => 2-2-1.txt
    [23] => 2-3.txt
    [231] => 2-3-1.txt
    [232] => 2-3-2.txt
    [2321] => 2-3-2-1.txt
)
Comments