-1

How can I sort this array in PHP? I want to have the most recent dates first. I can't do the sort in MySQL as the date field is coming from several different tables. Three rows shown here - there are more than 600 in total.

Array
(
    [0] => Array
        (
        Translator => Array
            (
                [id] => 1482
                [name] => Jane Doe
                [last_project] => (null)
            )
        )

    [1] => Array
        (
        Translator => Array
            (
                [id] => 1024
                [name] => John Doe
                [last_project] => 2013-06-25
            )
        )

    [2] => Array
        (           
        Translator => Array
            (
                [id] => 32
                [name] => Tom Doe
                [last_project] => 2009-07-10
             )
        )
)
gazareth
  • 1,135
  • 10
  • 26
  • 1
    http://php.net/manual/en/function.usort.php – CBroe Aug 02 '13 at 13:29
  • possible duplicate of [PHP Sort a multidimensional array by element containing date](http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date) – user247702 Aug 02 '13 at 13:32
  • show us the SQL Query, i'm sure it is sortable on the project if it spits out this array as a result... – NDM Aug 02 '13 at 13:34
  • I don't think so - I do one query to fetch all translators. Then loop through the results to find the most recent project date from one table. If no result found in that table, I do a second query to find the most recent project date from another table. – gazareth Aug 02 '13 at 13:36
  • 2
    and even if the result is coming for multiple different tables, I still think it's sortable by the DB, if you know how to use it. – STT LCU Aug 02 '13 at 13:36

2 Answers2

2
function sortFunction( $a, $b ) {
    return strtotime($a["last_project"]) - strtotime($b["last_project"]);
}
usort($array, "sortFunction");

Taken from PHP order array by date?

Community
  • 1
  • 1
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • Thanks, this works. I edited the form of my array above and had to edit the code here as well (added ['Translator'] in the callback function. Also had to reverse the array to get most recent first. – gazareth Aug 02 '13 at 13:39
1
function sortByDate($a, $b) {
    return $a['last_project'] - $b['last_project'];
}

usort($myArray, 'sortByDate');
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91