Sort array of objects

Oba*_*bay 6 php sorting oop multidimensional-array

I've had trouble with the examples in the PHP manual, so I'd like to ask this here...

I have an array of objects.. Is there a way to sort it based on the contents of the object?

For example, my array is:

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
        )
)
Run Code Online (Sandbox Code Playgroud)

How do I sort the array by the [alias] of the objects?

在示例中,输出应为:

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
        )
)
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Max*_*keh 8

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

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

$arr = ...;

usort($arr, 'my_comparison');
Run Code Online (Sandbox Code Playgroud)