0

资助几个函数来对数组进行排序,但如果它们是 stdClass 对象,它们都不能对它们进行排序,或者至少我找不到合适的

我需要通过排序值对这个数组进行排序

 [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 12
                            [name] => Title1
                            [ordering] => 1
                        )

                    [1] => stdClass Object
                        (
                            [id] => 14
                            [name] => Title2
                            [ordering] => 3
                        )

                    [2] => stdClass Object
                        (
                            [id] => 18
                            [name] => Title4
                            [ordering] => 2
                        )

                    [3] => stdClass Object
                        (
                            [id] => 22
                            [name] => Title5
                            [ordering] => 4
                        )

                )

任何帮助表示赞赏。谢谢!

4

2 回答 2

3

根据对象的字段定义自定义排序函数ordering,然后使用 usort 将其传入。

用于排序的文档

function sortByOrdering($obj1, $obj2) {
   return $obj2->ordering - $obj1->ordering;
}

usort($input['data'], 'sortByOrdering');

请注意,您不需要重新分配$input = usort(...),因为内部引用了数组usort

于 2012-05-17T01:55:33.123 回答
0

谢谢,斯干腾!这正是我一直在寻找的。

我注意到生成的排序顺序是降序的。我可以通过对您的函数进行简单更改来扭转这种情况 - 我在 return 语句中交换了 $obj1 和 $obj2 :

return $obj1->ordering - $obj2->ordering;

在我的应用程序中,数组数据是:

Array
(
    [3] => stdClass Object
        (
            [term_id] => 3
            [name] => Salesperson
            [slug] => 01-salesperson
            [term_group] => 0
            [term_order] => 0
            [term_taxonomy_id] => 3
            [taxonomy] => skill
            [description] => 
            [parent] => 0
            [count] => 6
            [object_id] => 53
        )

    [5] => stdClass Object
        (
            [term_id] => 5
            [name] => Airport Security
            [slug] => 02-airport-security
            [term_group] => 0
            [term_order] => 0
            [term_taxonomy_id] => 5
            [taxonomy] => skill
            [description] => 
            [parent] => 0
            [count] => 30
            [object_id] => 575
        )

    [4] => stdClass Object
        (
            [term_id] => 4
            [name] => Baker
            [slug] => 03-baker
            [term_group] => 0
            [term_order] => 0
            [term_taxonomy_id] => 4
            [taxonomy] => skill
            [description] => 
            [parent] => 0
            [count] => 28
            [object_id] => 453
        )
)

使用上述数据,我需要按“slug”值升序排列数组 $skills_nav。这是完成任务的最终代码:

function sortByOrdering($obj1, $obj2) {
   return $obj1->slug - $obj2->slug;
}
usort($skills_nav, 'sortByOrdering');

为了进一步向读者解释,函数 sortByOrdering 预期的两个参数由 USORT 自动提供。手册中的USORT功能对此进行了说明。

于 2013-03-02T22:36:51.530 回答