繁体   English   中英

PHP 如何通过两个索引对包含对象(stdClass)的对象(stdClass)进行排序?

[英]PHP How to sort object(stdClass) containing object(stdClass) by two indices?

我有以下需要排序的数据结构。 排序依据的第一个字段是“kategorie”,然后是“order_by”。 重要的是对象的键保持不变,网址在代码的其他部分中使用。

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'),      SORT_ASC,
                  $entries);

Edit2: 键入到数组并使用上述多重排序是答案。

它没有按预期工作,因为您是按字符串排序的,所以"10" < "2" 您可以将这些列转换为数字,或使用SORT_NUMERIC标志:

array_multisort(
    array_column($entries, 'kategorie'),
    SORT_NUMERIC,
    array_column($entries, 'order_by'),
    SORT_NUMERIC,
    $entries
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM