在PHP中按日期排序多维数组

时间:2013-04-10 07:08:13

标签: php json multidimensional-array

我想按日期在PHP中对数组进行排序,然后以JSON格式输出。我的数组包含很多“帖子”。以下是当我对当前数组进行json_encode并将其作为json回显时的当前状态。我想我可能不得不使用usort(),但我不知道该怎么做。

我已尝试过这个建议PHP Sort a multidimensional array by element containing date,但它对我不起作用。请任何人都可以帮忙。感谢

{
"post": [
    {
        "title": "Title 1",
        "date": {
            "strdate": "2013-04-09",
            "dayname": "Tue"
        }
    },
    {
        "title": "Title 2",
        "date": {
            "strdate": "2013-04-08",
            "dayname": "Mon"
        }
    }
]

}

PHP中的数组如下所示:

    <?php 

    Array
    (
        ["post"] => Array
            (
                [0] => Array
                    (
                        ["title"] =>   Title 
                        ["date"] => Array
                            (
                                ["strdate"] => 2013-04-09
                                ["month"] => 04
                                ["dayname"] => Tue
                            )

                    )

                [1] => Array
                    (
                        ["title"] =>   Title2 
                        ["date"] => Array
                            (
                                ["strdate"] => 2013-04-08
                                ["dayname"] => Mon
                            )

                    )

            )

    )

     ?>

2 个答案:

答案 0 :(得分:2)

usort($array['post'], function ($a, $b) {
    return strtotime($b['date']['strdate']) - strtotime($a['date']['strdate']);
});

答案 1 :(得分:1)

here

尝试此操作
function mysort($a, $b)
{
   return(strtotime($b['timestamp']) - strtotime($a['timestamp']));
}


// Convert first date & time to UNIX timestamp

$t1 = mktime(2, 30, 0, 7, 1, 2011);
$t2 = mktime(3, 30, 0, 7, 1, 2011);
$t3 = mktime(4, 30, 0, 7, 1, 2011);


// Store data to a Multidimensional Arrays
$testArray = array(
    "testing3" => array("timestamp" => $t1, 
                        "name" =>"testing3"),

    "testing" => array("timestamp" => $t2, 
                       "name" =>"testing"),

    "testing2" => array("timestamp" => $t3, 
                        "name" =>"testing2")
    );



usort($testArray, 'mysort');

echo "<pre>";
print_r($testArray);

echo "

";

foreach($testArray AS $row){

 $date = $row['timestamp'];
 echo date("d/m/y : H:i:s a",$date)."
";
}

另见: