按日期重新组织数组

时间:2013-08-19 11:43:19

标签: php

我正在尝试重新组织按日期排序的数组。

例如,这是我的数组:

Array(
      [0] => august 
      [1] => july 
      [2] => october 
      [3] => september
)

我如何按时间顺序重新组织它,所以它会变成这样:

Array(
      [0] => july 
      [1] => august 
      [2] => september 
      [3] => october
)

2 个答案:

答案 0 :(得分:1)

使用date_parse解析月份名称并将其转换为相应的数字,然后使用ksort对其进行排序。

$myArray = array('august', 'july', 'october', 'september');
foreach($myArray as $value) {
    $m = date_parse($value);
    $output[$m['month']] = ucfirst($value);
}
ksort($output);
print_r($output);

输出:

Array
(
    [7] => July
    [8] => August
    [9] => September
    [10] => October
)

来源:#12424968

<强> Demo!

答案 1 :(得分:1)

这适用于strtotime可以解析的任何日期

function cmp($a, $b) 
{
    $a_time = strtotime($a);
    $b_time = strtotime($b);
    if ($a_time == $b_time) {
        return 0;
    }
    return ($a_time < $b_time) ? -1 : 1;    
}


// Array to be sorted
$array = array('november', 'august', 'december', 'february');
print_r($array);

// Sort and print the resulting array
usort($array, 'cmp');
print_r($array);

输出:

Array
(
    [0] => november
    [1] => august
    [2] => december
    [3] => february
)
Array
(
    [0] => february
    [1] => august
    [2] => november
    [3] => december
)