2

我有以下代码:

$imageDir = "uploads/";
$allowedTypes = array('png', 'jpg', 'jpeg', 'gif');
$dimg = opendir($imageDir);
$images = array();

while ($imgfile = readdir($dimg)) {
    if (in_array(strtolower(substr($imgfile, -3)), $allowedTypes) || (in_array(strtolower(substr($imgfile, -4)), $allowedTypes))) {
        $images[] = $imgfile;

    }
}

基本上我还需要订购 $images 数组中的图像。例如我有 image-1.png, image-2.png, image-23.png, image-3.png ,我希望它们以正确的顺序存储在我的 $images 数组 (1, 2, 3, 23)不是 (1, 2, 23, 3)。

4

3 回答 3

1

您可以使用natsortPHP 内置的函数。这会将它们从最小到最大(就数字而言)、字母前的数字等进行排序。如果您需要以相反的顺序对它们进行排序,您可以array_reverse在排序后使用。

这是一个例子:

natsort($dirs); // Naturally sort the directories
$dirs = array_reverse($dirs); // Reverse the sorting
于 2013-02-26T19:29:35.263 回答
1

您需要在natsort此处使用,它以人类的方式对字母数字字符串进行排序。

.如果您要信任文件扩展名,您还应该在最后一个拆分(但我们不要这样做。您确实应该检查 mime 类型,但这是您可以作为家庭作业做的额外工作)

$image_dir = "uploads/";
$allowed_types = array('png', 'jpg', 'jpeg', 'gif');
$dimg = opendir($image_dir); // I vehemently follow my own style guide.
$images = array('png' => [], 'jpg' => [], 'jpeg' => [], 'gif' => []);
// all these people using pure array() when we've had the shorthand since php4...

while ($img_file = readdir($dimg)) {
    $ext = strtolower(end(explode(".", $img_file))); // end() is fun.
    if (in_array($ext, $allowed_types)) {
        $images[$ext][] = $img_file;
    }
}
foreach ($images as &$images_) { // pass-by-reference to change the array itself
    natsort($images_);
}

// $images is now sorted
于 2013-02-26T19:37:53.130 回答
0

你可以试试这段代码

$imageDir = "uploads/";
$allowedTypes = array('png', 'jpg', 'jpeg', 'gif');
$images = scandir($imageDir);

usort($images, function($file1, $file2){
    preg_match('/^image-(\d+)\./', $file1, $num1);
    preg_match('/^image-(\d+)\./', $file2, $num2);
    return $num1 < $num2 ? -1 : 1;
});

echo '<pre>' . print_r($images, 1) . '</pre>';
于 2013-02-26T19:32:13.707 回答