开发者

How to sort the following array?

I am fetching records from database which returns an array as follows:

Array
(
[0] => stdClass Object
    (
        [id] => 2
 开发者_C百科       [name] => ravi
        [text] => hey
        [date] => 2011-05-1
    )

[1] => stdClass Object

    (
        [id] => 3
        [name] => shiv
        [text] => bye
        [date] => 2011-04-29
    )

[2] => stdClass Object

    (
        [id] => 4
        [name] => adi
        [text] => hello
        [date] => 2011-04-30
    )
)

How to sort this based on the date element?


You should sort this before you actually fetch it, meaning use the 'ORDER BY' clause already in your database query!

Why?

  • because you write much less code
  • because it is faster
  • because it is easier to refactor


You may find the usort() function useful: http://docs.php.net/manual/en/function.usort.php

You could pass in as the second parameter the following function:

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


Ideally you should be sorting within the query itself, using ...ORDER BYdate..

..but if you really wanna do it with php, look at the user notes in the manual under sort, there are examples of how to sort like that (and you can apply with rsort() or asort() or arsort() depending on if you want to preserve keys or sort descending or whatever)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜