note 29955 added to function.array-multisort
| From: | dkampkas at ix dot urz dot uni-heidelberg dot de | Date: | Sun, 02 Mar 2003 04:07:42 +0000 |
| Subject: | note 29955 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-44719@lists.php.net to get a copy of this message | ||
I also tried dealing with sorting a multidim array and had some rather... let's say funny
experiences with it (to be honest, I almost threw my keyboard out of the windows...).
Okay, the situation: I had an array, made up as follows:
array (
[0] => array ( "size" => value, "rate" => value,...)
[1] => array ( "size" => value, ...)
...
)
Now, I wanted to sort them lets say by the value of "size". I tried the suggestions above,
but none worked (in fact, nothing happend, at least if PHP didn't complain about wrong syntax).
So I did make up a sort manually:
$ortarr=array($array[0][$column],$array[1][$column],...);
array_multisort($ortarr, $array);
This worked pretty fine. Then I tried a foreach loop:
$i=0;
foreach($array as $row){
$t = $array[$row][$column];
array_push($sortarr, $t);
$i++;
}
Comparison of the manual array and the array made up by foreach gave, they were identical. But - the
last one didn't work. And, even more interesting: Sorting by $ortarray only worked, if the loop
was commented out; if it wasn't, even $ortarray didn't work...
And this weird behaviour almost drove me mad...
But then I tried an even more simple way:
function csort($array, $column){
$i=0;
for($i=0; $i<count($array); $i++){
$sortarr[]=$array[$i][$column];
}
array_multisort($sortarr, $array);
return($array);
}
And, finally, it works.
But up to now I couldn't figure out neither what was the mistake of the first ones nor why the
hints from above didn't work... Next would be trying to do a sort for arrays whose toplevel
keys aren't integer but strings...
--
http://www.php.net/manual/en/function.array-multisort.php
http://master.php.net/manage/user-notes.php?action=edit+29955
http://master.php.net/manage/user-notes.php?action=delete+29955
http://master.php.net/manage/user-notes.php?action=reject+29955