资助几个函数来排序数组,但如果它们是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
)
)
任何帮助表示赞赏。谢谢!
答案 0 :(得分:3)
根据对象的ordering
字段定义自定义排序函数,然后使用usort传递它。
function sortByOrdering($obj1, $obj2) {
return $obj2->ordering - $obj1->ordering;
}
usort($input['data'], 'sortByOrdering');
请注意,由于$input = usort(...)
usort
答案 1 :(得分:0)
谢谢,SiGanteng!这就是我想要的。
我注意到生成的排序顺序正在下降。我能够通过对函数的简单更改来解决这个问题 - 我在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函数来解释。