对数组进行排序包含php中的日期

时间:2016-03-23 07:18:38

标签: php

我有一个像这样的数组我希望按日期排序这个数组如何对这个数组进行排序

$(window).resize(function() {
    area = 50000;
    width = $(window).width();
    fontSize= (Math.ceil(area/width));
    $('div').css('font-size', fontSize);
    }).resize();

我已经使用了usort但是它不起作用,我正在创建一个函数并将其转换为strtotime但它不起作用。任何建议。

2 个答案:

答案 0 :(得分:3)

尝试以下解决方案:

$array = array
(
    0 => '28/02/2016',
    1 => '30/01/2016',
    2 => '16/02/2016',
    3 => '19/02/2016',
    4 => '24/02/2016',
    5 => '13/02/2016',
    6 => '18/02/2016',
    7 => '27/02/2016',
    8 => '25/02/2016',
    9 => '01/02/2016',
    10 => '02/02/2016',
    11 => '03/02/2016',
    12 => '05/02/2016',
    13 => '06/02/2016',
    14 => '07/02/2016',
    15 => '08/02/2016',
    16 => '11/02/2016',
    17 => '12/02/2016'
);

function sortFunction( $a, $b ) {
    $date1 = DateTime::createFromFormat('d/m/Y', $a);

    $date2 = DateTime::createFromFormat('d/m/Y', $b);
    return $date1->getTimestamp() - $date2->getTimestamp();
}
usort($array, "sortFunction");
print_r($array);

<强>输出

Array
(
    [0] => 30/01/2016
    [1] => 01/02/2016
    [2] => 02/02/2016
    [3] => 03/02/2016
    [4] => 05/02/2016
    [5] => 06/02/2016
    [6] => 07/02/2016
    [7] => 08/02/2016
    [8] => 11/02/2016
    [9] => 12/02/2016
    [10] => 13/02/2016
    [11] => 16/02/2016
    [12] => 18/02/2016
    [13] => 19/02/2016
    [14] => 24/02/2016
    [15] => 25/02/2016
    [16] => 27/02/2016
    [17] => 28/02/2016
)

答案 1 :(得分:1)

使用sort()

尝试此操作
$array = array
(
    0 => '28/02/2016',
    1 => '30/01/2016',
    2 => '16/02/2016',
    3 => '19/02/2016',
    4 => '24/02/2016',
    5 => '13/02/2016',
    6 => '18/02/2016',
    7 => '27/02/2016',
    8 => '25/02/2016',
    9 => '01/02/2016',
    10 => '02/02/2016',
    11 => '03/02/2016',
    12 => '05/02/2016',
    13 => '06/02/2016',
    14 => '07/02/2016',
    15 => '08/02/2016',
    16 => '11/02/2016',
    17 => '12/02/2016'
);

foreach($array as $key=>$val) {
    $date_arr=explode('/',$val);
    $time_arr[$key]=strtotime($date_arr[2].'/'.$date_arr[1].'/'.$date_arr[0]);
}
sort($time_arr);
foreach($time_arr as $key=>$val) {
    $array[$key]=date("d/m/Y", $val);
}
echo '<pre>'; print_r($array); echo '</pre>';

输出

Array
(
    [0] => 30/01/2016
    [1] => 01/02/2016
    [2] => 02/02/2016
    [3] => 03/02/2016
    [4] => 05/02/2016
    [5] => 06/02/2016
    [6] => 07/02/2016
    [7] => 08/02/2016
    [8] => 11/02/2016
    [9] => 12/02/2016
    [10] => 13/02/2016
    [11] => 16/02/2016
    [12] => 18/02/2016
    [13] => 19/02/2016
    [14] => 24/02/2016
    [15] => 25/02/2016
    [16] => 27/02/2016
    [17] => 28/02/2016
)