Welcome Guest, Not a member yet? Register   Sign In
Multidimensional array sort by date
#1

[eluser]aniketharshe20[/eluser]
Hello,

I want to sort multidimensional array by date with descending order.
How to do it??

This my array:

Code:
Array
(
    [0] => stdClass Object
        (
            [comment_id] => 15
            [comment] => test
            [added_date] => 2012-10-29 17:38:27
            [user_id] => 1          
        )

    [1] => stdClass Object
        (
            [hubb_id] => 10
            [hubb] => test
            [added_date] => 2012-12-10 17:38:27
            [user_id] => 3
        )

    [2] => stdClass Object
        (
            [comment_id] => 15
            [comment] => test
            [added_date] => 2012-11-25 17:38:27
            [user_id] => 1
        )
)


---------------------------------------------
Thanks,
Aniket
#2

[eluser]jprateragg[/eluser]
I would sort it by date in your model/database query.
#3

[eluser]PhilTem[/eluser]
Either you do what @jprateragg suggests, or you have a look at
http://php.net/manual/en/array.sorting.php
and the mentioned functions for some of which you can define a custom search function that compares the added_date however you define i.e. want to compare it Wink
#4

[eluser]aniketharshe20[/eluser]
Hi,

I have mereged 2 arrays thats why they are not in order by date. I tried using array_multisort() but coudn't do it.


Thanks,
Aniket
#5

[eluser]jprateragg[/eluser]
Like I said--do this at your model level. Create a function your model that fetches both arrays. Use the UNION statement to merge the results so you can order by date relatively easily.
#6

[eluser]pickupman[/eluser]
@jprateragg has the best of doing it in the model, provided that a UNION will work. Otherwise you can use [url="http://php.net/manual/en/function.usort.php"]ursort()[/url]. Here's a quick comparison function that will work on your array.
Code:
function sort_by_date($a, $b)
{
if ($a->added_date == $b->added_date)
{
  return 0;
}

return ($a->added_date < $b->added_date) ? -1 : 1;
}

usort($yourData, 'sort_by_date');




Theme © iAndrew 2016 - Forum software by © MyBB