Sorting arrays within an array in PHP by datetime
arrays, datetime, php, sorting
Solution
Try this:
<?php
$a=array(
0 =>
array(
'post_id' => '1',
'user_id' => '3',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:40'
),
1 =>
array(
'post_id' => '2',
'user_id' => '2',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:39'
),
2 =>
array(
'post_id' => '3',
'user_id' => '5',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:38'
)
);
function cmp($a,$b){
return strtotime($a['created'])<strtotime($b['created'])?1:-1;
};
uasort($a,'cmp');
print_r($a);
?>
Problem
I currently have a problem within PHP where I want to sort these posts by their creation date so that they can then be shown in descending order. I have been looking for a PHP function to do this but have had no luck. Is there an easy solution to this? Any idea will be greatly appreciated :) ``` array 0 => array 'post_id' => string '1' (length=1) 'user_id' => string '3' (length=1) 'post' => string 'this is a post' (length=14) 'created' => string '2012-04-05 20:11:38' (length=19) 1 => array 'post_id' => string '2' (length=1) 'user_id' => string '2' (length=1) 'post' => string 'this is a post' (length=14) 'created' => string '2012-04-05 20:11:38' (length=19) 2 => array 'post_id' => string '3' (length=1) 'user_id' => string '5' (length=1) 'post' => string 'this is a post' (length=14) 'created' => string '2012-04-05 20:11:38' (length=19) ```