排序对象数组

时间:2010-01-23 04:02:56

标签: php oop sorting multidimensional-array

我在PHP手册中的示例遇到了问题,所以我想在这里问一下......

我有一个对象数组..有没有办法根据对象的内容对它进行排序?

例如,我的数组是:

Array
(
    [0] => stdClass Object
        (
            [id] => 123
            [alias] => mike
        )

    [1] => stdClass Object
        (
            [id] => 456
            [alias] => alice
        )

    [2] => stdClass Object
        (
            [id] => 789
            [alias] => zeke
        )

    [3] => stdClass Object
        (
            [id] => 987
            [alias] => dave
        )
)

如何通过对象的[别名]对数组进行排序?

在示例中,输出应为:

Array
(
    [0] => stdClass Object
        (
            [id] => 456
            [alias] => alice
        )

    [1] => stdClass Object
        (
            [id] => 987
            [alias] => dave
        )

    [2] => stdClass Object
        (
            [id] => 123
            [alias] => mike
        )

    [3] => stdClass Object
        (
            [id] => 789
            [alias] => zeke
        )
)

提前致谢!

2 个答案:

答案 0 :(得分:8)

使用usort()。您指定了一个执行该比较的函数,并根据该函数完成排序。 E.g:

function my_comparison($a, $b) {
  return strcmp($a->alias, $b->alias);
}

$arr = ...;

usort($arr, 'my_comparison');

答案 1 :(得分:2)

我认为订单丢失了,我发现了other function

<?php 
/** 
 * Sort array of objects by field. 
 * 
 * @autor Lea Hayes
 * @param array $objects Array of objects to sort. 
 * @param string $on Name of field. 
 * @param string $order (ASC|DESC) 
 */ 
function sort_on_field(&$objects, $on, $order = 'ASC') { 
    $comparer = ($order === 'DESC') 
        ? "return -strcmp(\$a->{$on},\$b->{$on});" 
        : "return strcmp(\$a->{$on},\$b->{$on});"; 
    usort($objects, create_function('$a,$b', $comparer)); 
}

$order = ($_GET['order'] === 'asc') ? 'ASC' : 'DESC';
sort_on_field($arr, 'alias', $order);