Gerardo Calixto Aquino Gerardo Calixto Aquino - 8 months ago 33
PHP Question

Sorting a array's numeric values without re-indexing (PHP)

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
    . this outputs ([1]=>1, [2]=>2, ...)

  • I then want to reorder the array in a descending order via the count

  • I then just use
    to get the IDs in a count ordered list.

I once used
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

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


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