【问题标题】:PHP How to sort object(stdClass) containing object(stdClass) by two indices?PHP如何通过两个索引对包含对象(stdClass)的对象(stdClass)进行排序?
【发布时间】:2021-08-17 22:39:39
【问题描述】:

我有以下需要排序的数据结构。排序依据的第一个字段是“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:键入到数组并使用上述多重排序就是答案。

【问题讨论】:

  • 标题错了,它不应该按索引排序,它应该按对象数据文件'order_by'和'kategorie'排序。
  • 这能回答你的问题吗? Sort multidimensional array by multiple columns
  • usor 不适用于 stdClass 对象,并且数组列答案对我的数据没有任何作用
  • 嗯,这个呢? stackoverflow.com/questions/4282413/… 如果您的数组来自json_decode() 调用,则将true 作为第二个参数传递以获取关联数组。

标签: php class sorting data-structures stdout


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 2011-12-30
    • 2012-06-23
    • 1970-01-01
    • 2021-06-05
    • 2020-01-08
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多