-2

553 / 5.000 Resultados de tradução Resultado da tradução I have a folder that basically contains other folders like 'NAME - H:I - D/M/Y' and 'NAME - PHONE - H:I - D-M-Y'. When I use PHP's scandir(), it sorts alphabetically, which is how folders naturally look on my server, but I'd like to somehow sort that scandir by date, then time, then names alphabetically. enter image description heremente.

I tried using date comparison and inserting it into another array (simply which one is older first), then the same with the time, but then everything went wrong.

I know that using the sort() function, I can arrange the dates and times for Y-m-d H:i:s using explode(), but because I have a name and phone, I couldn't.

I looked through the documentation, but nothing that seemed particularly helpful in this case https://www.php.net/manual/en_US/array.sorting.php.

  • "Everything went wrong" is not a clear enough description of a problem for us to help you solve. Click [edit] and include a [mre]: the code you wrote, the output or error it gives, and the output you want. – IMSoP Feb 26 '23 at 20:23

1 Answers1

0
$dir = "images";
$myArray=[];
$b = scandir($dir,1);
$ignored = array('.', '..', '.svn', '.htaccess'); 
foreach ($b as $file) {
if (in_array($file, $ignored)) continue; 
array_push($myArray,["file"=>$file,"datetime" =>date("F d Y H:i:s.", filectime($file))]);
}
// Comparison function
 function date_compare($element1, $element2) {

    $datetime1 = strtotime($element1['datetime']);

    $datetime2 = strtotime($element2['datetime']);

    return $datetime1 - $datetime2;
} 
// Sort the array 
usort($myArray, 'date_compare');

// Print the array
print_r($myArray)
alexandros
  • 22
  • 5
  • `$datetime1 - $datetime2` is no longer considered best practice -- the spaceship operator has been available for years. Why store the `filectime()` in a format which is not "big endian"? You are creating more work during the sorting process. I do not know if this script is reliably sorting by "date, then time, then names alphabetically". If you grabbed a portion of this script from another answer on Stack Overflow, you should be disclosing that information in your answer. – mickmackusa Feb 27 '23 at 02:23