如何解决PHP如何通过两个索引对包含对象stdClass的对象stdClass进行排序?
我有以下需要排序的数据结构。要排序的第一个字段是“kategorie”,然后是“order_by”。重要的是对象的键保持不变,url 会在代码的其他部分使用。
object(stdClass)#2 (31) {
["https://idp1.xxx/idp/shibboleth"]=>
object(stdClass)#12 (4) {
["name"]=>
string(19) "test"
["data"]=>
string(39) "test"
["kategorie"]=>
string(1) "2"
["order_by"]=>
string(3) "200"
}
["https://idp2.xxx/idp/shibboleth"]=>
object(stdClass)#1 (4) {
["name"]=>
string(52) "test"
["data"]=>
string(60) "test"
["kategorie"]=>
string(1) "3"
["order_by"]=>
string(3) "110"
}
["https://idp3.xxx/idp/shibboleth"]=>
object(stdClass)#1 (4) {
["name"]=>
string(52) "test"
["data"]=>
string(60) "test"
["kategorie"]=>
string(1) "2"
["order_by"]=>
string(3) "120"
} ...
它应该是什么样子:
object(stdClass)#2 (31) {
["https://idp3.xxx/idp/shibboleth"]=>
object(stdClass)#1 (4) {
["name"]=>
string(52) "test"
["data"]=>
string(60) "test"
["kategorie"]=>
string(1) "2"
["order_by"]=>
string(3) "120"
}
["https://idp1.xxx/idp/shibboleth"]=>
object(stdClass)#12 (4) {
["name"]=>
string(19) "test"
["data"]=>
string(39) "test"
["kategorie"]=>
string(1) "2"
["order_by"]=>
string(3) "200"
}
["https://idp2.xxx/idp/shibboleth"]=>
object(stdClass)#1 (4) {
["name"]=>
string(52) "test"
["data"]=>
string(60) "test"
["kategorie"]=>
string(1) "3"
["order_by"]=>
string(3) "110"
} ...
实现这一目标的最简单方法是什么?我只是无法绕过它...
编辑:usort 不适用于 stdClass 对象 这个 array_multisort 也不起作用
array_multisort(array_column($entries,'kategorie'),SORT_ASC,array_column($entries,'order_by'),$entries);
Edit2: Typcasting to array and the using above multisort is the answer.
解决方法
它没有按预期工作,因为您是按字符串排序的,所以 "10" < "2"
。您可以将这些列转换为数字,也可以使用 SORT_NUMERIC
标志:
array_multisort(
array_column($entries,'kategorie'),SORT_NUMERIC,array_column($entries,'order_by'),$entries
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。