-1

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,
        "imageurl" => "http://images.com/img.jpg"
    )

    array (
        "name" => "c",
        "followers" => 15,
        "imageurl" => "http://images.com/img.jpg"
    )

)

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 :)!!

Community
  • 1
  • 1
Avicinnian
  • 1,822
  • 5
  • 37
  • 55

2 Answers2

1

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.

Matchu
  • 83,922
  • 18
  • 153
  • 160
  • 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 00: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 00:51
0

array_multisort() is what you are after.

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

array_multisort($followers,SORT_DESC,$name,SORT_ASC,$en_array);

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

DaveRandom
  • 87,921
  • 11
  • 154
  • 174