牛骨文教育服务平台(让学习变的简单)
博文笔记

PHP 根据对象属性进行对象数组的排序

创建时间:2018-02-01 投稿人: 浏览次数:437

根据对象属性进行对象数组的排序【转自 stackoverflow 】
Sort array of objects by object fields

Question
How can I sort this array of objects by one of its fields, like name or count ?

  Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [name] => Mary Jane
            [count] => 420
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [name] => Johnny
            [count] => 234
        )

    [2] => stdClass Object
        (
            [ID] => 3
            [name] => Kathy
            [count] => 4354
        )

   ....

Answer :
Use usort, here’s an example adapted from the manual:

function cmp($a, $b)
{
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

edits imported from comments:

If you’re sorting the array from inside the class and your sorting function cmp is also defined inside the class, then use this:

usort($your_data, array($this, "cmp"))

参考:

https://stackoverflow.com/questions/4282413/sort-array-of-objects-by-object-fields#

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。