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

What I'm doing is this:

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?

Upvotes: 2

Views: 5040

Answers (5)

Travis Miller
Travis Miller

Reputation: 26

There are valid use cases where you might not be able to pre-sort result sets in your query and need to use array_multisort. Here's an example of how you might go about doing so while maintaining your original key association.

// Let's say your data is a hash lookup where the key is important.
$user_ids = array_keys($users);
// You want to sort by username so copy those values.
$usernames = array_column($users, 'username');
// Now sort your arrays.
array_multisort($usernames, SORT_ASC, $user_ids, $users);
// Simply recombine your keys and values.
$users = array_combine($user_ids, $users);

Upvotes: 0

PiotrN
PiotrN

Reputation: 310

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].

Upvotes: 0

Peter Schuetze
Peter Schuetze

Reputation: 16305

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

Upvotes: 1

chelmertz
chelmertz

Reputation: 20601

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

Upvotes: 2

Gumbo
Gumbo

Reputation: 655239

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

Upvotes: 7

Related Questions