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
Sorting an array
Moderator: General Moderators
-
visionmaster
- Forum Contributor
- Posts: 139
- Joined: Wed Jul 14, 2004 4:06 am
O.k, usort() sorts an array by values using a user-defined comparison function.feyd wrote:usort()
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!
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
Try this, I read through it and it looks like you can use that last bit of code to solve your problem
-
visionmaster
- Forum Contributor
- Posts: 139
- Joined: Wed Jul 14, 2004 4:06 am
Thanks for the link, but I don't exactly see the hint you gave me, since there is a lot of code...Cronikeys wrote: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
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
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.
-
visionmaster
- Forum Contributor
- Posts: 139
- Joined: Wed Jul 14, 2004 4:06 am