Page 1 of 1
Sorting an array
Posted: Sun Jan 16, 2005 12:21 pm
by visionmaster
Hello together,
What ist the quickest and best way to sort an array by its elements? Does PHP maybe even have an array-function which does the following:
Suppose an array holding these elements:
b
a
a
c
c
b
a
I would like to sort the array by the number of elements and sort the output by the number of times the element was found descending, e.g. like this:
a 3
b 2
c 2
Howto?
Thanks
Posted: Sun Jan 16, 2005 12:37 pm
by feyd
usort()
Posted: Sun Jan 16, 2005 1:27 pm
by visionmaster
feyd wrote:usort()
O.k, usort() sorts an array by values using a user-defined comparison function.
So in the function cmp() I have to take care of the details? What do I have to do? Take the first element of my array and walk through the array using a for loop? if the element found is identical then the counter is increased. After that I know how often the element in array[0] was found. Oops, I'm just noticing that I have to discard the identical elements from my array or I will search for just this element once again.
Hmm, any example out there? Are my thoughts going the correct direction?
---------
I found following example, but don't really understand what happens. I don't understand what e.g. $b holds?
function cmp ($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$a = array (3, 2, 5, 6, 1);
usort ($a, "cmp");
while (list ($key, $value) = each ($a)) {
echo "$key: $value\n";
Thanks for your help!
Posted: Sun Jan 16, 2005 1:47 pm
by Cronikeys
http://terra.di.fct.unl.pt/docs/php/fun ... rt.php.htm
Try this, I read through it and it looks like you can use that last bit of code to solve your problem

Posted: Sun Jan 16, 2005 1:56 pm
by visionmaster
Thanks for the link, but I don't exactly see the hint you gave me, since there is a lot of code...
Posted: Sun Jan 16, 2005 7:25 pm
by feyd
the user defined function passed to usort is a simple comparator of the two elements of the array passed to it. If I remember correctly, returning negative one tells the bubble sort the left hand element is less than the right, and there for will be moved. Returning one has the opposite effect. Zero tells the sort they are equal, and to do nothing.
Posted: Mon Jan 17, 2005 7:03 am
by visionmaster
How then do can I transform an array to an assoziative array, in which the keys are the values of the original array?
Thanks!
Posted: Mon Jan 17, 2005 7:57 am
by feyd
uasort()
