----- Original Message -----
From: "bryan_is_south"
Hello,
I have a multidimensional array, and would like to sort it by the
value of the last array.
Here's the idea of what I've got:
$Scores[$artist][$album]=$avg;
So the $Scores array contains an array for each artist, and each
$artist array contains an array for each album by them. The value for
the $album array is the average score for the album.
I want to sort this multidimensional array by the $avg, but I can't
figure it out.
Suggestions are much appreciated.
Thank you in advance
-bryan
------------------------------------
Hi Bryan,
This can be done with a bubble sort but bubble sorts are slow.
PhP has an inbuilt sort function sort() but it is intended for flat arrays
and not multi dimensional.
The first question that has to be asked is if the results are ranked by
album irrespective of artist or if the results must still have albums by an
artist still grouped together.
If they don't have to grouped by artist then you really do have to convert
to a flat array as a multi dimensional array does not reflect this
structure.
Here is the basic structure of a bubble sort that can be expanded to multi
dimensions but remember the inbuit sort() function will be much faster for
flat arrays.
// to bubble sort flat array $array[] in ascending order ...
for($end_compare_index=count($array) - 2, $end_compare_index >= 0,
$end_compare_index--)
{
for($compare_index = 0, $compare_index <= $end_compare_index,
$compare_index++)
{
if(array[$compare_index] > array[$compare_index + 1))
{
$temp = $array[$compare_index];
$array[$compare_index] = $array[$compare_index + 1];
$array[$compare_index + 1] = $temp;
}
}
}
The above is just hand typed so it may have typo's.
I think that the best solution is to have a second flat associative array
that represents the sort order of the first indexed multi dimensional array.
Tell me more about the needed output structure and what it is to used for
and I will send some code.
Thanks, Robert.