There are lots of PHP defined function to order arrays (the core of PHP, technically are hashmaps), ordering by value or keys, preserving key order or not, using an user-defined function, normal or reverse order, etc...
Following, some clear example of the main ones, and some tips about how to remember them
ORDER BY VALUE
sort():  order by VALUE  (keys destroyed and renumberted starting from zero)
$a = array('z'=>'A', 'y'=>'C','k'=>'B','x'=>'B');
sort( $a );  # Array (   A  ,B ,B ,C ) 
asort():  as the previous, but it maintains index association
$a = array('z'=>'A', 'y'=>'C','k'=>'B','x'=>'B');
asort( $a ); # Array (   [z] => A ,  [k] => B ,  [x] => B  , [y] => C ) 
natsort():  use "natural" sorting
$a = array('z'=>'5p', 'y'=>'10p','20p');
sort( $a ); # Array (  10p ,20p  ,5p )
natsort( $a ); # Array (   [2] => 5p ,  [0] => 10p  , [1] => 20p ) 
ORDER BY KEY
ksort():  order by key (maintaining associations)
$a = array('z'=>'A', 'y'=>'C','k'=>'B','x'=>'B');
ksort( $a );  # Array (   [k] => B ,  [x] => B  , [y] => C  , [z] => A ) 
USER-DEFINED COMPARISON FUNCTION
usort(): compare using an user-defined function. (keys destroyed and renumbered starting from zero)
$a = array( '0'=>array('id'=>4,'n'=>'aaa') , '1'=>array('id'=>2,'n'=>'bbb')
usort($a, function ($a, $b) { #order by '[id]' contained in the elements #closure (php 5.3)
                                 return ($a['id'] < $b['id']) ? -1 : 1;               }); #Array (  Array  (  [id] => 1  [n] => ccc  )  ,Array  (  [id] => 2  [n] => bbb  ) ,Array  (  [id] => 4  [n] => aaa  )  ) 
uasort(): as usort but MAINTAINS the KEYS
HOW TO REMEMBER FUNCTION NAMES
sort = default sort behaviour: order by value and destroy keys
If the function name contains:
u = sort using [U]ser-defined function  (Usort, Uasort, Uksort)
a = [A]ssociative: maintains key order (Asort, Arsort, uAsort)
k = order by [K]ey   (Ksort, Krsort)
r = [R]everse order (aRsort, kRsort, Rsort)
OTHER ARRAY USEFUL FUNCTIONS
shuffle(): scramble array s contents. (keys destroyed and renumberted starting from 0)
array_rand($array, $number): return $number random elements from $array
array_multisort()
array_shift( array &$array ) ; return the array shifted by 1element off the beginning of array (remove the 1st)
array_slice( array $array , 3, 2, $preserve_keys); RETURNS 2 elements starting from the 4th. if $preserve_keys is true, the keys in the return array are the same in the original one
$a = array(0=>1, 1=>2, 2=>3, 4=>4, 3=>5, 5=>6);
$a = array_slice($a,3,2); #Array (  4 ,5 ) 
array_splice(): remove the slice  (REFERENCE) and return the removed part
$a = array(1, 2, 3, 4, 5, 6);
$returned = array_splice($a,3,2);  #remove 2 elements from 4th elem. return the  removed slice
# $returned = Array (  4 ,5 )
# $a = Array (   1 ,2 , 3 ,  6 ) 
 
No comments:
Post a Comment