0

I have two questions:

1) I'm use the below code to output a list of sub-directories contained in the folder 'issues'. Each sub-directory is a number. I'd like to sort that output by increasing value, so 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 20, 21 etc.

How can I do this?

<?php

chdir('issues');
$d = dir(".");

echo "<ul>";

while (false !== ($entry = $d->read()))
{
 if (is_dir($entry) && ($entry != '.') && ($entry != 'sponsors') && 
 ($entry != '..'))
 echo "<li><a href='{$entry}'>{$entry}</a></li>";
}

echo "</ul>";

$d->close();

?>

2) On a different part of the same page, I also want to output a link to the latest issue, i.e. the sub-directory with the highest number. How would I do that?

Thank you!

Kai
  • 157
  • 1
  • 1
  • 9

1 Answers1

1

Use scandir() with array_slice to get a sorted array of the directory contents.

Use asort for accurate numerical sorting as dossy suggested.

$directory = 'issues';
$contents = array_slice(scandir('issues'), 2);
$sub_dirs = array();
foreach($contents as $c){
   $path = $directory."/".$c;
   if(is_dir($path) && $c !== 'sponsors'){
      $sub_dirs[] = $c;
   }
}
asort($sub_dirs, SORT_NUMERIC);
$latest = end($sub_dirs);
reset($sub_dirs);
echo '<ul>';
foreach($sub_dirs as $sub){
   echo '<li><a href="'.$directory.'/'.$sub.'">'.$sub.'</a></li>';
}
echo '</ul>';
echo '<a href="'.$directory.'/'.$latest.'">'.$latest.'</a>';
KFish
  • 440
  • 3
  • 9
  • 1
    `scandir()` does not sort numerically, but lexicographically. https://stackoverflow.com/questions/6810619/how-to-explain-sorting-numerical-lexicographical-and-collation-with-examples – dossy Oct 06 '18 at 18:33
  • 1
    you could `asort($contents)` to numerically sort the list – dossy Oct 06 '18 at 18:35
  • Thank you so much! The first part works flawlessly, but the second part spits out a few files I have in the parent folder instead of the sub-directory with the highest number. Any ideas? Thank you! – Kai Oct 06 '18 at 18:57
  • Oh, yeah that would be because when you used scandir, you actually retrieved the whole contents of the parent directory (including those files). When I realized that I missed the 2nd part of your question and added that to the answer, I forgot about that part. From the first part where you loop through the contents and filter out only the directories, you could use that same logic to just put only those directories into another array instead, and then grab the end of that array. – KFish Oct 08 '18 at 03:16