从当前月份开始对glob数组进行排序

时间:2015-03-30 07:59:16

标签: php arrays sorting foreach glob

我在一个glob画廊工作,它显示每个月的均匀(如图所示)。 这是我的代码:

$folderGlob = glob("gallery/events/2015/*/");
foreach($folderGlob as $folder){
    $fileglob = glob($folder . "*.{jpg,png}", GLOB_BRACE);
    foreach($fileGlob as $file){
        // lets say i dont have images, but i just echo $file
        echo $file;
    }
}

输出将如下:

gallery/events/2015/01/01.jpg
gallery/events/2015/02/04.jpg
gallery/events/2015/03/09.jpg
gallery/events/2015/04/21.jpg
gallery/events/2015/05/04.jpg
gallery/events/2015/06/09.jpg
gallery/events/2015/07/21.jpg
... etc

正如您所见,我的地图结构就像日期一样,文件名为日,地图名称为月。现在我需要对此进行排序,以便首先显示当前的mont。

这里是我想要的例子:

gallery/events/2015/03/09.jpg //current month
gallery/events/2015/04/21.jpg
gallery/events/2015/05/04.jpg
gallery/events/2015/06/09.jpg
gallery/events/2015/07/21.jpg
... 
gallery/events/2015/12/02.jpg //lastmonth
gallery/events/2015/01/01.jpg 
gallery/events/2015/02/04.jpg

任何提示或技巧?

编辑: 我现在用这个:

$currentMonth = date("m");
$month = intval($currentMonth);

foreach ($folderGlob as $folder) {
    $folderMonth = intval(basename($folder));
    if($folderMonth < $month){
        continue;
    } else {
        print $folderMonth . '<br>';
    }
}

foreach ($folderGlob as $folder) {
    $folderMonth = intval(basename($folder));
    if($folderMonth >= $month){
        continue;
    } else {
        print $folderMonth . '<br>';
    }
}

输出是:

gallery/2015/03/
gallery/2015/04/
gallery/2015/05/
gallery/2015/06/
gallery/2015/07/
gallery/2015/08/
gallery/2015/09/
gallery/2015/10/
gallery/2015/11/
gallery/2015/12/
gallery/2015/01/
gallery/2015/02/

1 个答案:

答案 0 :(得分:-1)

使用自定义排序功能:

$array = array('gallery/events/2015/01/01.jpg',
'gallery/events/2015/02/04.jpg',
'gallery/events/2015/05/04.jpg',
'gallery/events/2015/04/21.jpg',
'gallery/events/2015/06/09.jpg',
'gallery/events/2015/03/09.jpg',
'gallery/events/2015/07/21.jpg');

usort($array, function($a, $b) {

    $currentmonth = date('n');
    preg_match('#^gallery/events/(\d+)/(\d+)/(\d+)\.jpg$#', $a, $matchesa);
    preg_match('#^gallery/events/(\d+)/(\d+)/(\d+)\.jpg$#', $b, $matchesb);

    $timea = mktime(0, 0, 0, $matchesa[2], $matchesa[3], $matchesa[1]);
    $timeb = mktime(0, 0, 0, $matchesb[2], $matchesb[3], $matchesb[1]);

    $montha = (int)$matchesa[2];
    $monthb = (int)$matchesb[2];



    if ( 
        ($montha > $currentmonth && $monthb > $currentmonth) ||
        ($montha < $currentmonth && $monthb < $currentmonth) ||
        ($montha == $currentmonth && $monthb == $currentmonth) )
        {
            if ( $timea < $timeb ) return -1;
            else if ( $timea > $timeb ) return 1;
            else return 0;
        }
        else
        {
            if ( $montha < $currentmonth ) return 1;
            else if ( $montha > $currentmonth ) return -1;
            else return 0;
        }
});


print_r($array);

Here是一项有效的测试。