对象的数组排序对象的数组排序(Sort array of objects)

2019-05-12 06:15发布

我已经与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
        )
)

提前致谢!

Answer 1:

使用usort() 您可以指定一个函数来做到这一点比较和排序是基于函数来完成。 例如:

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

$arr = ...;

usort($arr, 'my_comparison');


Answer 2:

我认为,为了丢失,我发现这个其他功能

<?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);


文章来源: Sort array of objects