ThomasReggi
ThomasReggi

Reputation: 59345

Ordering a array holding objects by object data

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;
}

Upvotes: 0

Views: 79

Answers (1)

Sajid
Sajid

Reputation: 4421

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;
}

Upvotes: 3

Related Questions