Take the 2-minute tour ×

Possible Duplicate:
Sort an array by a child array's value in PHP

I have the following array structure:

$en_array = array();

while(...) {
    $en_array[] = $row;

$en_array = array (
    array (
        "name" => "a",
        "followers" => 5,
        "imageurl" => "http://images.com/img.jpg"

    array (
        "name" => "b",
        "followers" => 25,

    array (
        "name" => "c",
        "followers" => 15,


In this example I would like to order the keys of en array by the values of followers, e.g. $en_array[0]["followers"] would have the value of 25.

I'm not entirely sure if this can be done, but I hope it can.

Any help will be much appreciated :)!!

share|improve this question

marked as duplicate by Robert Harvey Aug 31 '11 at 2:42


So we're sorting by followers, then? –  Matchu Aug 31 '11 at 0:38
Yeah, purely by followers :). –  Avicinnian Aug 31 '11 at 0:44

2 Answers 2

up vote 1 down vote accepted

Since it looks like you're only interested in sorting by followers, we can do this easily with PHP's usort.

function compare_by_followers($a, $b) {
    if($a['followers'] == $b['followers']) return 0;
    return $a['followers'] > $b['followers'] ? -1 : 1;

usort($en_array, 'compare_by_followers');

Sorting is, at its core, a process of comparing the array's elements to each other and figuring out which ones are greater than the others. usort allows you to use a custom comparison function for this process: compare_by_followers($a, $b) returns -1 if $a['followers'] is greater than $b['followers'] (meaning that $a should go before $b), returns 1 if $a['followers'] is less than $b['followers'] (meaning that $a should come after $b), and returns 0 if they are equal.

share|improve this answer
Note that my first draft of this answer had it backwards and sorted in ascending order. If you're looking for descending, use the new snippet. (The only difference is I replaced the < in the function with >.) –  Matchu Aug 31 '11 at 0:45
Thanks, especially for the explanation!! So I take it that it gradually filters down comparing each array (I'm not really sure of what $a and $b represent)? –  Avicinnian Aug 31 '11 at 0:51

array_multisort() is what you are after.

foreach ($en_array as $key => $row) {
    $name[$key] = $row['name'];
    $followers[$key] = $row['followers'];


After this, results are in descending order of followers, and where followers are the same, ascending order of name (i.e. alphabetical order).

share|improve this answer
