views:

262

answers:

4

What I'm doing is this:

  • I get a list of ID values (numeric) from the DB and store it into an array (1, 2, 2, ...)
  • I then count the duplicates with array_count_values. this outputs ([1]=>1, [2]=>2, ...)
  • I then want to reorder the array in a descending order via the count
  • I then just use array_keys($array) to get the IDs in a count ordered list.

I once used array_multisort for a similar function but in that case the keys were strings ('a'=>2). The problem now is that I'm using numeric keys and multisort re-indexes the keys to 1, 2, 3 because the keys holding the count value are numeric IDs. This of course screws the purpose 'cause I can't identify anything anymore..

Anyway, here's what I'm roughly doing now:

$array = array(3, 1, 2, 3, 2, 3);
// count the IDs [0]=>3, [1]=>1, [2]=>2

$count = array_count_values($array);

// sort and screw up the id's: [0]=>3 [1]=>1 [2]=>2
array_multisort($count);

Something tells me that there's a better way of approaching this?

+4  A: 

Try asort instead of array_multisort as it maintains the original index association.

Gumbo
Thanks... that was simple but is there any easy way to sort it in a descending list? My original use of multisort was because of this.
@transient-jet-lag: You can either use `arsort` (`r`=reverse) or use `array_reverse` after `asort`.
Gumbo
+1  A: 

Guessing from your first sentence:

I get a list of ID values (numeric) from the DB and store it into an array (1, 2, 2, ...)

perhaps you could do the sorting whilst querying, something like this:

SELECT id, COUNT(id) AS quantity FROM table GROUP BY id ORDER BY quantity DESC
chelmertz
Hey, thanks. There you go, I always miss the most obvious thing.
Yeah you did, but giving a detailed background on the question is the next best thing :)
chelmertz
A: 

Why do you need to do it with php? Change your SQL statement to give you the correct results. something like

select ID, count(another_col) as occurrence
from table
group by ID
sort by occurrence

For the right SQL syntax see http://www.techonthenet.com/sql/group_by.php

edit: ups missed the sorting criteria. It must be by occurrence and not by ID

Peter Schuetze
For the right SQL syntax see http://www.techonthenet.com/sql/order%5Fby.php ;-)
Gumbo
You are rigth, with group by it needs to be order by. How can I have missed that? ;)
Peter Schuetze
A: 

As others mentioned, if you can get the data sorted from the database, it might be better. If You want to do it in PHP and need reversed order, use [arsort][1].

PiotrN