CodeIgniter Forums
Multidimensional array sort by date - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Multidimensional array sort by date (/showthread.php?tid=56320)



Multidimensional array sort by date - El Forum - 12-10-2012

[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


Multidimensional array sort by date - El Forum - 12-10-2012

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


Multidimensional array sort by date - El Forum - 12-10-2012

[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


Multidimensional array sort by date - El Forum - 12-10-2012

[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


Multidimensional array sort by date - El Forum - 12-11-2012

[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.


Multidimensional array sort by date - El Forum - 12-11-2012

[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');