Sunday, 22 June 2014

Sorting Arrays In PHP

there are two ways to sort elements of array. If you want a simple default ascending order sorting with non-object array elements, then you can go for “sort” function. You just pass the array as parameter and it will sort the array and returns true if succeed.
1
2
3
4
$simple_array = array("dbc","bcd,"abc");
if(sort($simple_array)){
print_r($simpl_array);
}

If you want to define your own logic for sort condition and/or you are using objects as element of array, go for “usort” function. Example:
01
02
03
04
05
06
07
08
09
10
11
12
13
$elements = array();
 
$elements[0] = (object)NULL;
$elements[0]->post_time = new DateTime();
 
$elements[1] = (object)NULL;
$elements[1]->post_time = new DateTime();
 
usort($elements,"sort_function");
 
function sort_function( $a, $b ) {
   return $b->post_time->diff($a->post_time)->invert;
}

No comments:

Post a Comment