php - ajax php图像按字母顺序排列

标签 php

header('Content-Type: application/json');
$folder = $_POST['folder'];
$dir = $folder."/";
//start directory 
$dirHandle = opendir($dir); 
$i = 0;
$directoryfiles = array();

while ($file = readdir($dirHandle)) {
    //check only image type file.
    if(!is_dir($file) && preg_match("/.png|.jpg|.gif/i", $file)){
        $i++;
        $totalfiles = "$dir$files";
        $src = $totalfiles;
        $temp = new stdClass;
        $temp->num = $i;
        $temp->src = $src;
        $temp->name = $files;
        $directoryfiles["img".$i] = $temp;
    }
}

// close directory
closedir($dirHandle);

//turn array to json
echo json_encode($directoryfiles);

我正在使用 ajax 从 php 获取图像返回,我遇到的问题是图像没有像文档那样按字母顺序排列。

我尝试使用 sort($directoryfiles),但没有用。

我如何确保我的图像按照文档的字母顺序排列? scandir() 对我有帮助吗?这里需要帮助。谢谢

conlog的归来

image3-000000-023.png
image2-000000-022.png
image1-000000-021.png
image4-000000-024.png

我需要的顺序

image1-000000-021.png
image2-000000-022.png
image3-000000-023.png
image4-000000-024.png

最佳答案

您可以使用 asort为您的解决方案。

asort - Sort an array and maintain index association

看例子:

$directoryfiles = array("image3-000000-023.png", "image2-000000-022.png", "image1-000000-021.png", "image4-000000-024.png");

//Sort array using asort() function...Place below single line after while loop into your code
asort($directoryfiles);

//Print output...
print('<pre>');
print_r($directoryfiles);
print('</pre>');

//Output...
Array
(
    [2] => image1-000000-021.png
    [1] => image2-000000-022.png
    [0] => image3-000000-023.png
    [3] => image4-000000-024.png
)

您可以看到 asort() 的输出就像您想要的那样。

有关实际示例,您可以查看 PHPFIDDLE .单击运行 - F9 并查看输出。

关于php - ajax php图像按字母顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868687/

相关文章:

PHP:如何从 foreach 循环内部修改数组(通过引用)

javascript - 如何在 PHP 中使用弹出窗口获取变量?

javascript - 如果选中单选按钮,则在 Codeigniter 中显示 div

php - 如何在 View laravel blade 的类中添加运算符三元?

php - 序列化/反序列化 php 对象

php - MySQL - 预替换

php - 验证/允许YouTube嵌入代码

php - 获取一张表的所有数据,而另一张表为空且也应用where子句

php - 警告 : openssl_pkcs7_sign() [function. openssl-pkcs7-sign] : error getting private key in C:\xampp\htdocs\this\tcpdf\tcpdf. php on line 8366

PHP mySql 更新在本地主机上运行良好,但在实时运行时运行不佳