André Nęss <an*********************@ifi.uio.no> wrote in message news:<bp**********@maud.ifi.uio.no>...
Terence:
lawrence wrote:
Is there an easy way to sort a 2 dimensional array alphabetically by
the second field in each row?
Also, when I use sort() on a two dimensional array, it seems to work a
lot like array_reverse(). Can anyone tell me why?
You can always resort to using a bubble sort when sorting requirements
become, er, different.
Be aware that bubble sort is generally considdered an expensive way to
do things.
Well as long as you have usort() I don't see the point. Why specify the
entire algorithm when all you really need to do is specify the comparison
function?
André Nęss
I started trying to work it out, but in the end I couldn't. I can
figure out how to sort a one dimensional array, but not a two
dimensional array.
This is as close as I got:
$twoDArray;// already given a 2 d array
$newArray = array(); // to store the new, sorted array
for ($i=0; $i < count($twoDArray); $i++) {
$row = $twoDArray[$i];
$headline1 = $twoDArray[$i][1];
$firstCharacter = $headline1[0];
$r = $i + 1;
$headline2 = $twoDArray[$r][1];
$firstCharacter2 = $headline2[0];
$yesOrNo = cmp($headline1, $headline2);
if ($yesOrNo == 1) $newArray[] = $row;
}
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
This would, I think, arrange the rows by the ASCII value of the first
character of the second field in each row, which still isn't
alphabetical, but it is closer.
?>