0

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

Array
(
[0] => stdClass Object
    (
        [id] => 2
        [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?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

and dont forget to add an index for the date field
Thanks markus, But actually i can't use order by clause. Bcoz it is inside another foreach loop and i am simply making an array of data inside it.
2

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;
}

3 Comments

you might actually need this php.net/manual/en/arrayobject.uasort.php then use the above function with $arrayObject->uasort('cmp'); however you should also convert the dates to timestamp before directly comparing with < and >
Yeah, or write a heavy framework for sorting arrays coming directly from the DB... :P
@venimus you're right, I erroneously assumed they were strings: in that case the string operators (<,>) would work.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.