Order this array by date modified?

社会主义新天地 提交于 2019-11-28 10:10:41

问题


I have a php file that is creating a array of everything in my users directory, the array is then being sent back to a iPhone.

The array that my php is creating is ordering them alphabetically, i want it to sort by the date the file was created..

Here is what my php file looks like

<?php
$username = $_GET['username'];
$path = "$username/default/";


$files = glob("{$path}/{*.jpg,*.jpeg,*.png}", GLOB_BRACE);

// output to json
echo json_encode($files);

?>

How would i do this?

Thanks :)


回答1:


Using usort() with a callback which calls filemtime()...

This is untested, but I believe it will set you on the correct path...

// First define a comparison function to be used as a callback
function filetime_callback($a, $b)
{
  if (filemtime($a) === filemtime($b)) return 0;
  return filemtime($a) < filemtime($b) ? -1 : 1; 
}

// Then sort with usort()
usort($files, "filetime_callback");

This should sort them oldest-first. If you want them newest-first, change < to > in the callback return ternary operation.




回答2:


As Michael Berkowski mentioned, using usort() is the way to go, but if this is a one-off sorting (i.e. you only need to sort an array this way once in your code), you can use an anonymous function:

usort($files, function ($a, $b){
    if (filemtime($a) === filemtime($b)) return 0;
    return filemtime($a) < filemtime($b) ? -1 : 1; 
});

While not necessary, it does save a function call.

If you need to sort files this way more than once, creating a separate named function is preferable.



来源:https://stackoverflow.com/questions/7948300/order-this-array-by-date-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!