ruyelpequenocid
ruyelpequenocid

Reputation: 55

Natural Order needed for directory list

I am new to PHP and I need assistance making this bit work. I am trying to have the directory folders listed in a PHP page. So far it is working but the list of folders appears in "Standard" order. I need it in "Natural" order but I cannot make it work.

Standard Order:

Natural Order:

Here is what I have so far:

<?php

$TheFolder = '';

foreach(glob($TheFolder.'*', GLOB_ONLYDIR) as $dir) {
    $dir = str_replace($TheFolder, '', $dir);
    echo $dir , "<br>";
    //echo $dir;
}

?>

I have been trying to use natsort before but could not figure it out.

Any help would be very appreciated.

Upvotes: 0

Views: 89

Answers (2)

ruyelpequenocid
ruyelpequenocid

Reputation: 55

Thanks to Mostafa Mohsen who pointed me in the right direction.

Taking Mostafa's solution as base, a small modification was needed as it was still throwing an error.

This is the final code, working ok:

<?php

$directoriesArray = glob('*', GLOB_ONLYDIR);
sort($directoriesArray, SORT_NATURAL);
foreach($directoriesArray as $dir){
    echo $dir , "<br>";
}
?>

Upvotes: 0

Mostafa Mohsen
Mostafa Mohsen

Reputation: 786

You can use sort() function with SORT_NATURAL flag on;

Like so:

$array = [1,10,11,12,4,30];
sort($array, SORT_NATURAL);
print_r($array); // Array ( [0] => 1 [1] => 4 [2] => 10 [3] => 11 [4] => 12 [5] => 30 )

So something like this should work:

$directoriesArray = glob($TheFolder.'*', GLOB_ONLYDIR);
sort($directoriesArray, SORT_NATURAL);
foreach($directoriesArray as $dir){
//.. str_replace and echo $dir
}

Read more about sort() function here

Upvotes: 2

Related Questions