【问题标题】:PHP code not sorting array of folder images by datePHP代码不按日期对文件夹图像数组进行排序
【发布时间】:2023-01-11 02:07:56
【问题描述】:

我正在从文件夹加载图像 (.jpg) 以显示在 html 页面中。我能够加载照片并输出到 html,但它们没有按日期顺序排序。我没有看到任何错误,我也没有看到/理解为什么 echo 没有输出到任何地方供我调试。

<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

// Set the path to the folder containing the images
$folder = 'c:/wamp/www/PhotoGallery/images';

// Get an array of all image files in the folder
$files = array_filter(glob($folder2 . '*.{jpg,jpeg,png,gif}', GLOB_BRACE), 'is_file');

// Sort the files by modification time using a custom sort function
usort($files, function($a, $b) { return filemtime($a) < filemtime($b); });

// Print the sorted list of image file names
foreach ($files as $file) {
    echo basename($file) . PHP_EOL; 
}

// Remove the "." and ".." entries from the array
$files = array_diff($files, array('.', '..'));

// Return the array as a JSON object
echo json_encode($files);

?>

我在网上搜索并尝试了各种解决方案均无济于事。我知道 js 但不知道 PHP,所以我可能缺少一些简单的东西(语法?)。 我还阅读了 PHP 文档以了解这些功能。

我阅读了其他 stackflow 答案,但收到此错误: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

【问题讨论】:

  • 您可能需要这里的宇宙飞船操作员:return filemtime($a) &lt;=&gt; filemtime($b);

标签: php arrays image sorting


【解决方案1】:

您的排序功能只返回 true 或 false。 php函数正在寻找3个返回值-101

https://www.php.net/manual/en/function.usort.php

正如使用 &lt;=&gt;(太空飞船操作员)的 cmets 中提到的那样,您可以执行所需的操作:

usort($files, function($a, $b) { return filemtime($a) &lt;=&gt; filemtime($b); });

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多