-2

I have multidimensional array with many values, this is minimized version of it:

$test = array(
    array(
       'name'   => 'test',
       'date'   => '2012-04-30 11:06:01'
    ),

    array(
       'name'   => 'test2',
       'date'   => '2012-04-30 11:07:00'
    )
);

And it just goes on...

Now dates are in random order, so i need to sort this array so it would be from smallest date to the biggest one, to be more clear i here is my full scale array dump: http://pastebin.com/EzTNJpUx and as you can see sent is the date and it goes in random order...

Linas
  • 4,380
  • 17
  • 69
  • 117
  • What have you tried? Also, there are *many* duplicates of this question on SO -- try searching some more. – Jon Apr 30 '12 at 08:35
  • possible duplicate of [Sort php multidimensional array by sub-value](http://stackoverflow.com/questions/4508145/sort-php-multidimensional-array-by-sub-value) – Jon Apr 30 '12 at 08:37

3 Answers3

3

Use usort

From Manual:

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

function cmp($a, $b){
     return strtotime($a['date'])-strtotime($b['date']);
}

usort($test, 'cmp');
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

Guess you could use something like this,

usort() and DateTime class(if your using PHP5 or higher).

You you need to define a function to compare two elements(in this case, arrays also).

function cmp($array1, $array2)
{
  $date1 = new DateTime($array1['sent']);
  $date2 = new DateTime($array2['sent']);

  if($date1 == $date2)
    return 0;

  return ($date1 < $date2) ? -1 : 1;
}

then you call :

usort($test, 'cmp');
ehanoc
  • 2,187
  • 18
  • 23
1

I would go for array_multisort().

CDuv
  • 2,098
  • 3
  • 22
  • 28