【问题标题】:How do I sort alphabetically with pictures in php?如何在php中按字母顺序对图片进行排序?
【发布时间】:2018-04-18 15:28:51
【问题描述】:

这是我的数组 基本上现在我有一个包含 100,000 张图像的目录。都是不同的名称,例如 d2jd29df.png fj329f.png 等。我希望它在网页上按字母顺序列出它们。有人可以在正确的方向上推动我吗?

img 1 of code

img 2 of code

【问题讨论】:

  • 到目前为止您尝试过什么?发布您的一些代码,以便我们提供帮助
  • 请把代码添加为代码,而不是没有人会点击的图片:)

标签: php sorting arraylist


【解决方案1】:

您需要将整个目录读入一个数组,然后按字母顺序自然地(即人类的方式)对数组进行排序。最后,迭代每个文件并回显每个文件的文件名。

<?php
$files  = array();
$dir    = '/path/to/images';
$handle = opendir($dir);

if ($handle) {
    while (false !== ($file = readdir($handle))) {
        if ($file !== '.' && $file !== '..') {
            $files[] = $file;
        }
    }
    closedir($handle);
}
sort($files, SORT_NATURAL);

foreach ($files as $file) {
    echo $file.'<br />';
}

【讨论】:

  • 为了测试这一点,我在目录中放了 4 张图片,1.png、3.png、2.png、4.png。这样做,我使用了你的代码,它没有对图像进行排序。相反,它在旁边添加了文本。该文本已排序。
【解决方案2】:

试试这个:

<?php
$dir = "path/to/image";

$images = glob("$dir/*.*");

$items = [];
foreach ($images as $image) {
    $items[] = basename($image);
}
sort($items, SORT_STRING);

foreach ($items as $item) {
    echo $item . '<br>';
}

将 $dir 的值更改为包含图像的目录。

【讨论】:

    【解决方案3】:

    最简单的方法是使用scandir()

    $contents = array_diff(scandir('/path/to/my/images/folder'), array('.', '..'));
    
    // If you need to apply a custom sorting algorithm then try using
    // natsort(), natcasesort(), usort(), or uasort() on $contents
    // before looping through it.
    //
    // http://php.net/manual/en/array.sorting.php
    
    foreach($contents as $item)
    {
        echo $item;
    }
    

    另外,您不妨查看scandir()sorting_order 参数。

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2021-12-09
      • 1970-01-01
      • 2010-12-12
      • 2011-08-29
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多