【问题标题】:PHP function - Ordering of readdir file listing is oddPHP 函数 - readdir 文件列表的顺序是奇怪的
【发布时间】:2014-02-04 10:49:27
【问题描述】:

我有一些 PHP 脚本可以读取图像目录并回显用户搜索的结果。

我需要找到一种方法从目录中对这些搜索结果进行排序,我知道您可以在数组上使用 natsort() 但这无济于事,因为结果不在数组中,只是一个 while 语句。

有谁知道这是否可行?或者也许更容易调整我的代码以首先将文件名添加到数组中?

  <?php
    $dir = get_post_meta($post->ID, "Library", true);
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                if(stristr($file,$_POST['image_search'])){
                    echo ('<li><div class="thumb-contain"><a href="/'.$dir . $file.'" class="photo-link" rel="attachment"><img src="/asset-thumbs/'. $file .'" /></a><br/><p><a href="/'.$dir . $file.'" class="photo-link" target="_blank">View image</a> | <a href="/download.php?download_file='.$dir . $file.'">Download image</a> <p>'. $file .'</p></div></li>');
                }
            }
            closedir($dh);
        }
    }
  ?>

好的,我通过将结果添加到数组中来让它工作 - 我不是 PHP 向导,所以如果有人发现任何可能更清洁的东西,那就太棒了,否则感谢您的帮助。

<?php
$dir = get_post_meta($post->ID, "Library", true);
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if(stristr($file,$_POST['image_search'])){
                $files[] = $file;
            }
        }
        closedir($dh);
        natsort($files);
            foreach($files as $file) {
                echo ('<li><div class="thumb-contain"><a href="/'.$dir . $file.'" class="photo-link" rel="attachment"><img src="/asset-thumbs/'. $file .'" /></a><br/><p><a href="/'.$dir . $file.'" class="photo-link" target="_blank">View image</a> | <a href="/download.php?download_file='.$dir . $file.'">Download image</a> <p>'. $file .'</p></div></li>');
            }
    }
}
?>

【问题讨论】:

  • 为什么不遍历 readdir 结果并将项目添加到数组中。然后对该数组进行排序?

标签: php readdir opendir


【解决方案1】:

您可以使用函数scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] ) - 它返回数组并支持排序选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多