Right, I think this is a tricky one, but then I would say that, I'm the one that's stuck with it 🙂
Here's the array I'm using as a test case. The array is called $test
Array
(
[0] => Array
(
[0] => Array
(
[product_code] => 10448
[product_name] => Musicology
[artist_name] => PRINCE
[price] => 8.99
)
[1] => Array
(
[product_code] => 9232
[product_name] => Songs about Jane
[artist_name] => MAROON 5
[price] => 8.99
)
[2] => Array
(
[product_code] => 9205
[product_name] => Scissor Sisters
[artist_name] => SCISSOR SISTERS
[price] => 8.99
)
[3] => Array
(
[product_code] => 10524
[product_name] => WESTWOOD: THE JUMP OFF
[artist_name] => Various
[price] => 12.99
)
)
[1] => Array
(
[other_data] => there is different, differently structured data over here which is completely independant
)
)
Now, looking at the man page for [man]array_multisort[/man] and [man]usort[/man] I found a couple of solutions for ordering by one of the keys (in these example 'price'), here they are below.
array_multisort with temp array
$orderby='price';
foreach($test[0] as $val)
$sortarray[]=$val[$orderby];
array_multisort($test[0],$sortarray);
usort
$orderby='price';
function opensort($a, $b) {
global $orderby;
if(empty($a[$orderby])) return -1;
if(empty($b[$orderby])) return 1;
if($a[$orderby]>$b[$orderby]) return 1;
}
usort($test[0],'opensort');
I've even implemented a quicksort for it!
function quicksort(&$arary, $lo, $hi, $column) {
$i=$lo;
$j=$hi;
$x=$array[0][($lo+$hi)/2][$column];
do {
while($array[0][$i][$column] > $x) ++$i;
while($array[0][$j][$column] < $x) --$j;
if($i<=$j) {
$h=$array[0][$i];
$array[0][$i]=$array[0][$j];
$array[0][$j]=$h;
$i++; $j--;
}
} while($i<=$j);
if($lo<$j) quicksort($array, $lo, $j, $column);
if($i<$hi) quicksort($array,$i, $hi, $column);
}
quicksort($test,0,count($test),'price');
All work fine if I only want to order by one key but what I want to achive is a sort similar to MySQL's ORDER BY where I can order by one value and then order by another value within the limits of the first sort. This is doing my head in.
Any ideas?
Thanks
Bubble