note 11162 deleted from function.sort by irc-html

From: Date: Sat, 19 Jan 2002 22:13:50 +0000
Subject: note 11162 deleted from function.sort by irc-html
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-25515@lists.php.net to get a copy of this message
Hi, if you want to sort an multi dimensional array by its for example second element, you can't use any of PHP's builtin functions, I think. Example: $array = Array( Array("element1","4","element3"), Array("element1","3","element3"), Array("element1","1","element3"), Array("element1","2","element3") ); You want the array to be sortet like this: $array = Array( Array("element1","1","element3"), Array("element1","2","element3"), Array("element1","3","element3"), Array("element1","4","element3") ); The solution is a quicksort function: function qsort_multiarray($array,$num = 0,$left = 0,$right = -1) { if($right == -1) { $right = count($array) - 1; } $links = $left; $rechts = $right; $mitte = $array[($left + $right) / 2][$num]; if($rechts > $links) { do { while($array[$links][$num]<$mitte) $links++; while($array[$rechts][$num]>$mitte) $rechts--; if($links <= $rechts) { $tmp = $array[$links]; $array[$links++] = $array[$rechts]; $array[$rechts--] = $tmp; } } while($links <= $rechts); $array = qsort_multiarray($array,$num,$left, $rechts); $array = qsort_multiarray($array,$num,$links,$right); } return $array; } $array = qsort_multiarray($array,2,0,count($array)-1); The first argument is the array itself, the second the index of the sort criterium, the third the left start index, the fourth and last argument is the right index of the field. The last two arguments are optional, I implemented them because it could be that someone want's to sort only a part of the array. Greets, CK1 http://wwwtech.de

« previous php.notes (#25515) next »