Search code examples
phparrayssortingfilenames

Sort subdirectory names downloaded from within them


I have a directory, I sort the names of its subdirectories. But these are numerical names (plant identification numbers). I would like to have the plant names displayed rather than their ID numbers. In each subdirectory I have a txt file containing the name of the plant. I display it in the menu next to the plant ID number. But I would like to have the plant names (not ID!!) sorted in ascending order.

The file with the plant name has a title >> "id plant"_info_01c.txt <<

$taxon = ID Plant = name of subdirectory

The name of the plant >> $file_info_01c_text << is a link to iframe.

I would like to ask for the simplest possible solution for possible repair by a novice in the times of fallout. If a database is needed, it should only be in txt.

<?php

$path = ".";
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        
        $taxon = $fileinfo->getFilename();
        $file_info_01c = $taxon.'/'.$taxon.'_info_01c.txt';
        // wczytanie pliku 'info_01c.txt'
        $file_info_01c_text = file_get_contents($file_info_01c);

        echo $taxon.' &nbsp;  <A href="index-if.php?taxon='.$taxon.'" target="ramka">'.$file_info_01c_text.'</A><br>';
    }
}

?>

Solution

  • Add your data to an array and sort it before you echo the link.

    $plants = [];
    
    foreach (new DirectoryIterator(".") as $fileinfo) {
        if ($fileinfo->isDir() && !$fileinfo->isDot()) {
            $taxon = $fileinfo->getFilename();
            $plants[] = [
                'name'  => file_get_contents("{$taxon}/{$taxon}_info_01c.txt"),
                'taxon' => $taxon,
            ];
        }
    }
    
    // Sort results by the file text
    usort($plants, fn($a, $b) => $a['name'] <=> $b['name']);
    
    // Create the links here instead
    foreach ($plants as $plant) {
        $name  = $plant['name'];
        $taxon = $plant['taxon'];
        echo "{$taxon} &nbsp; <a href=\"index-if.php?taxon={$taxon}\" target=\"ramka\">{$name}</a><br>";
    }