对从其中下载的子目录名称进行排序[重复]

问题描述 投票:0回答:1

我有一个目录,我对其子目录的名称进行排序。但这些是数字名称(植物识别号)。我希望显示植物名称而不是 ID 号。在每个子目录中,我都有一个包含植物名称的 txt 文件。我将其显示在工厂 ID 号旁边的菜单中。但我希望植物名称(不是 ID!!)按升序排序。

带有植物名称的文件的标题>>“id plant”_info_01c.txt <<

$taxon = ID 植物 = 子目录名称

植物名称>> $file_info_01c_text << is a link to iframe.

我想寻求最简单的解决方案,以便新手在辐射发生时进行修复。如果需要数据库,则只能是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>';
    }
}

?>
php arrays sorting filenames
1个回答
0
投票

将数据添加到关联数组并在回显链接之前对其进行排序。

<?php
$path = ".";
$dir = new DirectoryIterator($path);
$folders = [];

foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        $taxon = $fileinfo->getFilename();
        $file_info_01c = $taxon . '/' . $taxon . '_info_01c.txt';
        $file_info_01c_text = file_get_contents($file_info_01c);

        $folders[] = [
            'taxon' => $taxon,
            'file_info_01c_text' => $file_info_01c_text
        ];
    }
}

// Sort results by the file text
usort($folders, function ($a, $b) {
    return strcmp($a['file_info_01c_text'], $b['file_info_01c_text']);
});

// Create the link here instead
foreach ($folders as $folder) {
    $taxon = $folder['taxon'];
    $file_info_01c_text = $folder['file_info_01c_text'];
    echo $taxon . ' &nbsp;  <A href="index-if.php?taxon=' . $taxon . '" target="ramka">' . $file_info_01c_text . '</A><br>';
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.