01 <?php
02
03 function array_multi_sort($array, $index, $order='desc', $natural_sort=FALSE, $case_sensitive=FALSE)
04 {
05 if(is_array($array) && count($array)>0)
06 {
07 foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
08 if(!$natural_sort) ($order=='asc')? asort($temp) : arsort($temp);
09 else
10 {
11 ($case_sensitive)? natural_sort($temp) : natcasesort($temp);
12 if($order!='asc') $temp=array_reverse($temp,TRUE);
13 }
14 foreach(array_keys($temp) as $key)
15 (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
16 return $sorted;
17 }
18 return $array;
19 }
20
21 // demo of complex array sorting
22
23 $demoarray = array(
24 'whatever'=>array(
25 'first'=>25,
26 'second'=>'fred'
27 ),
28 'whatever2'=>array(
29 'first'=>36,
30 'second'=>'simone'
31 ),
32 'whatever3'=>array(
33 'first'=>12,
34 'second'=>'tom'
35 ),
36 'whatever4'=>array(
37 'first'=>3,
38 'second'=>'peter'
39 ),
40 'whatever5'=>array(
41 'first'=>56,
42 'second'=>'maria'
43 )
44 );
45
46 $sortorder = 'desc';
47 $index = 'first';
48
49 $demoarray = array_multi_sort($demoarray, $index,$sortorder);
50
51 echo '
52 <p>
53 array sorted by fieldname "'.$index.'" in '.$sortorder.'ending order
54 </p>
55 <p>';
56 foreach($demoarray as $row)
57 {
58 echo '
59 '.print_r($row,true).'<br />';
60 }
61 echo '
62 </p>';
63
64 $sortorder = 'asc';
65 $index = 'second';
66
67 $demoarray = array_multi_sort($demoarray, $index,$sortorder);
68
69 echo '
70 <p>
71 array sorted by fieldname "'.$index.'" in '.$sortorder.'ending order
72 </p>
73 <p>';
74 foreach($demoarray as $row)
75 {
76 echo '
77 '.print_r($row,true).'<br />';
78 }
79 echo '
80 </p>';
81
82
83 ?>