Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

php - Sort array of objects

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

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

In the example, the output should be:

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

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use usort(). You specify a function to do that comparison and the sort is done based on the function. E.g.:

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

$arr = ...;

usort($arr, 'my_comparison');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...