Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

sorting

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?

like image 227
Gerardo Calixto Aquino Avatar asked Nov 19 '25 09:11

Gerardo Calixto Aquino


1 Answers

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

like image 165
Gumbo Avatar answered Nov 21 '25 23:11

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!