按对象数据排序保存对象的数组

时间:2011-09-11 07:19:14

标签: php arrays sorting object

我正在尝试找到一种通过深层对象项排序数组的有效方法,下面是示例:

阵列方案:

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

所需结果降序:

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

任何人都可以比这更好吗?或者可能改进它?

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 个答案:

答案 0 :(得分:3)

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