0

I am trying to find an efficient way of ordering a array by a deep object item, here is the example:

array scheme:

array
  [0] = animal
    count->1
    name->tiger
  [1] = animal
    count->3
    name->lion
  [2] = animal
    count->4
    name->monkey
  [3] = animal
    count->2
    name->elephant

Desired Result descending:

array
  [2] = animal
    count->4
    name->monkey
  [1] = animal
    count->3
    name->lion
  [3] = animal
    count->2
    name->elephant
  [0] = animal
    count->1
    name->tiger

Can anyone do one better than this? or possibly improve it?

function order_by_count($animals){
    $animals_order = array();
    foreach($animals as $key => $animal){
        $animals_order[$key] = $animal->count;
    }
    natsort($animals_order);
    $master_animals_order = array_reverse(array_keys($animals_order));  
    $revised_animals = array();
    foreach($master_animals_order as $key){
        $animal = $animals[$key];
        $revised_animals[] = $animal;
    }   
    return $revised_animals;
}
1
  • 1
    Did you have a look into usort? Commented Sep 11, 2011 at 7:28

1 Answer 1

3

User usort.

function animal_compare_function($v1, $v2) {
    if ($v1->count == $v2->count) return 0;
    return ($v1->count < $v2->count) ? 1 : -1; // note -1 and 1 are reversed since we're sorting descending.
}

function order_by_count($animals) {
    usort($animals, 'animal_compare_function');
    return $animals;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.