Reputation: 1808
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)
Upvotes: 5
Views: 6988
Reputation: 53573
You can use strtotime()
to convert the timestamp to an integer.
Upvotes: 1
Reputation: 1457
Sorting array of records/assoc_arrays by specified mysql datetime field and by order:
function build_sorter($key, $dir='ASC') {
return function ($a, $b) use ($key, $dir) {
$t1=strtotime(is_array($a)?$a[$key]:$a->$key);
$t2=strtotime(is_array($b)?$b[$key]:$b->$key);
if($t1==$t2) return 0;
return (str_to_upper($dir)=='ASC'?($t1 < $t2):($t1 > $t2)) ? -1 : 1;
};
}
// $sort - key or property name
// $dir - ASC/DESC sort order or empty
usort($arr, build_sorter($sort, $dir));
Upvotes: 2
Reputation: 9874
You can sort an array using a custom sort function, like so:
function cmp($a, $b) {
if($a['created'] < $b['created']) {
return 1;
} else if ($a['created'] > $b['created']) {
return -1;
} else {
// The only option left is that they are equal
return 0;
}
}
usort($array, cmp);
For more information about usort, check the php manpage
Upvotes: 1
Reputation: 64526
You can use the usort() function which allows you to sort an array based on your own criteria.
function cmp($a, $b)
{
if ($a['created'] == $b['created']) {
return 0;
}
return ($a['created'] < $b['created']) ? 1 : -1;
}
usort($myArray, "cmp");
print_r($myArray);
Or if you want to convert to a time:
function cmp($a, $b)
{
if ($a['created'] == $b['created']) {
return 0;
}
$aInt = strtotime($a['created']);
$bInt = strtotime($b['created']);
return ($aInt < $bInt) ? 1 : -1;
}
Upvotes: 1
Reputation: 42642
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);
?>
Upvotes: 5