uasort strange problem [message #173429] |
Tue, 12 April 2011 22:38 |
Peter
Messages: 15 Registered: March 2003
Karma:
|
Junior Member |
|
|
Hi all,
I currently have a list of products stored in a multi-dimensional array
which contains, amongst other fields, the product's name, heading
'name', and the product's price, heading 'price' and I want to be able
to sort the array by name ascending/descending and price
ascending/descending.
The array is originally created from a mysql database using various
tables and so I have not been able to create a simple, mysql query that
allows me to return the data already sorted. There are various reasons
for this which I don't wish to go into here, being a php forum.
So I found out about the uasort function, plus a small routine that
seemed to be just what I was looking for to allow me to sort on either
'name' or 'price' ascending. I then discovered the array_reverse
function which I thought would allow me to reverse the array to allow me
to have 'name' or 'price' descending options.
At least that's what I thought, but I'm new to both functions and so I
might be missing something obvious and so hope that someone here can
point out my mistakes.
Here's the problem. If I just compare on either 'name' or 'price'
ascending the array remains unsorted. If I compare on either 'name' or
'price' ascending and then use the array_reverse function it works like
a charm and the array is perfectly sorted in descending order. So what
I'm not getting is this, how can an array that remains unsorted when
using either of my compare functions, suddenly become sorted when
reversed?
Hope someone here can explain.
Here is the php that I am using to sort the array:
switch($searchtype){
case '1':
uasort($array, 'compare_nameAsc'); // sort on name ascending
break;
case '2':
uasort($array, 'compare_nameAsc'); // sort on name ascending
$array = array_reverse($array); // reverse the sort order
break;
case '3':
uasort($array, 'compare_priceAsc'); // sort on price ascending
break;
case '4':
uasort($array3, 'compare_priceAsc'); // sort on price ascending
$array = array_reverse($array); // reverse the sort order
break;
}
And here are the 2 functions:
function compare_nameAsc($a, $b)
{
return strnatcmp($a['name'], $b['name']);
}
function compare_priceAsc($a, $b)
{
return strnatcmp($a['price'], $b['price']);
}
--
Pete Ives
Remove All_stRESS before sending me an email
|
|
|