views:

707

answers:

5

I have an array of string keys with numeric values for use in a list of tags with the number of occurances of each tag, thus:

$arrTags['mango'] = 2;
$arrTags['orange'] = 4;
$arrTags['apple'] = 2;
$arrTags['banana'] = 3;

this is so i can display the tag list in descending occurance order thus:

orange (4)
banana (3)
mango (2)
apple (2)

i can use arsort to reverse sort by the value which is brilliant but i also want any tags that have the same numeric value to be sorted alphabetically, so the final result can be:

orange (4)
banana (3)
apple (2)
mango (2)

is there a way i can do this? i'm guessing that usort may be the way to go but i look at the examples on php.net and my eyes glaze over! many thanks!!!

A: 

I haven't tried it, but have you tried sorting the keys ascending first, then sorting the values descending?

It seems that most sorts won't move elements around if they're already the same.

R. Bemrose
+2  A: 

Have a look at examples #3: http://uk.php.net/manual/en/function.array-multisort.php

You'll need to create two arrays to use as indexes; one made up of the original array's keys and the other of the original array's values.

Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).

SlappyTheFish
This is more complicated than necessary
Michael Mior
A: 

You can just create a function to create an empty array and insert them in order based on comparisons.

Stanislav Palatnik
+1  A: 

You're thinking too complicated:

ksort($arrTags);
arsort($arrTags);

Now your array is sorted like you want it to.

Tatu Ulmanen
I was just about to post this exact answer. Anyway, tried it and I can confirm it works.
Michael Mior
php sorts aren't stable, so you aren't guaranteed this will work. http://www.php.net/manual/en/array.sorting.php
chris
@chris, that's true but I still haven't found any cases where it would not work, so I'd go on with this.
Tatu Ulmanen
thanks for the idea but it doesn't work for me. it's sorted the numbers descending fine but the key sorting for the same numerical values is pretty random, certainly not alphabetical. not sure why though.
David
+1  A: 

SOLVED

After a little experimenation I discovered that array_multisort does the trick nicely:

$tag = array();
$num = array();

foreach($arrTags as $key => $value){
$tag[] = $key;
$num[] = $value;
}

array_multisort($num, SORT_DESC, $tag, SORT_ASC, $arrTags);

:)

David
That would be SlappyTheFish's answer, right? I think you should mark that answer as accepted and then look at the array_keys() and array_values() functions to get rid of your loop.
Scott Saunders