【问题标题】:php read directory sortingphp读取目录排序
【发布时间】:2013-08-07 18:15:27
【问题描述】:

我有一个小 php 脚本,它读取一个目录,然后将所有文件(在本例中为 jpg)回显到一个 jquery 图像滑块中。它工作得很好,但我不知道如何按名称降序对图像进行排序。目前图像是随机的。

<?php
$dir = 'images/demo/';
if ($handle = opendir($dir)) {

while (false !== ($file = readdir($handle))) {
    echo '<img src="'.$dir.$file.'"/>';
}

closedir($handle);
}
?>

对此的任何帮助都会很棒。

还有一件事我不明白。该脚本在该文件夹中拍摄了 2 个不存在的无名非 jpg 文件???但我还没有真正检查过

【问题讨论】:

  • “然后回显所有文件(在这种情况下为 jpg)” 鉴于 $dir = 'images/demo/'; 假设您只有 .jpg 文件。如果没有,它将显示其中的每个文件。你可以改用foreach (glob("folder/*.jpg") as $dir) {
  • @OP (Piet Bez) 如果您觉得有人回答了您的问题并且问题已解决,您可以接受一个,以便将其标记为已解决。否则,它将保持“未答复”。干杯(和平

标签: php readdir


【解决方案1】:

试试这个:

$dir = 'images/demo/';
$files = scandir($dir);
rsort($files);
foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo '<img src="' . $dir . $file . '"/>';
    }
}

【讨论】:

  • 这个OR应该是AND
  • 谢谢,这很好用。我相信其他建议也会起作用。这个看起来最简单。只有一个问题。我不明白排序部分。目前它对图像进行排序,我怎么能对它们进行排序,使其降序?我需要最高值 10.jpg 排在第一位,1.jpg 排在最后。
  • 默认是升序,你可以使用rsort降序,答案已更新
  • @ManojYadav Manoj 干得好!干杯
  • @PietBez Manoj 做得很好,但我必须指出,确保您的文件夹中只有 .jpg 文件。如果您有“索引”文件或任何其他不是图像的文件,则会显示为损坏的图像。只是觉得你应该意识到这一点。干杯(P.s.:我并没有从 Manoj 的回答中拿走,这是一个很好的回答):) (Peace)
【解决方案2】:

尝试将每个项目放入一个数组中,然后对其进行排序:

$images = array();

while (false !== ($file = readdir($handle))) {
    $images[] = $file;
}

natcasesort($images);

foreach ($images as $file) {
    echo '<img src="'.$dir.$file.'"/>';
}

【讨论】:

  • 太好了,这是实现排序的最小侵入性更改。
【解决方案3】:

编辑:

使用 asort() 函数排序版本。

asort()升序-arsort()倒序

<?php

// You can use the desired folder to check and comment the others.
// foreach (glob("../downloads/*") as $path) { // lists all files in sub-folder called "downloads"
foreach (glob("images/*.jpg") as $path) { // lists all files in folder called "test"

    $docs[$path] = filectime($path);
} arsort($docs); // sort by value, preserving keys

foreach ($docs as $path => $timestamp) {

// additional options
//    print date("d M. Y: ", $timestamp);
//    print '<a href="'. $path .'">'. basename($path) .'</a>' . " Size: " . filesize($path) .'<br />';

echo '<img src="'.$path.$file.'"/><br />'; 
}
?>


上一个答案

使用 glob( ) 函数。

利用glob()功能,您可以根据自己的喜好设置文件和文件夹。

More on the glob( ) PHP.net 上的函数

要显示所有文件,请使用(glob("folder/*.*")

<?php

foreach (glob("images/*.jpg") as $file) { //change "images" to your folder
    if ($file != '.' || $file != '..') {
    
// display images one beside each other.
// echo '<img src="'.$dir.$file.'"/>';

// display images one underneath each other.
    echo '<img src="'.$dir.$file.'"/><br />'; 

    }
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多