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

2
  • What have you tried? Also, there are many duplicates of this question on SO -- try searching some more. Commented Apr 30, 2012 at 8:35
  • possible duplicate of Sort php multidimensional array by sub-value Commented Apr 30, 2012 at 8:37

3 Answers 3

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

Comments

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

Comments

1

I would go for array_multisort().

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.