dpdyh86002 2017-04-18 00:50
浏览 82
已采纳

如何对包含对象的三维数组进行排序?

I'm building a WordPress site where I need to sort the results of a WP_User_Query AFTER the query has already been run. For those of you not familiar, it has elements that look like this:

Array (
  [0] => WP_User Object (
    [data] => stdClass Object (
      [ID] => 1
      [user_login] => MarvinLazer
      [user_pass] => $P$BUGHRCjMzlvn7dlGp53UTPC8GMF081/
      [user_nicename] => marvinlazer
      [user_email] => marvin@lazer.com
      [user_url] => http://marvinlazer.com
      [user_registered] => 2017-03-04 23:08:08
      [user_activation_key] =>
      [user_status] => 0
      [display_name] => Marvin Lazer
    )
    [ID] => 1
    [caps] => Array (
      [subscriber] => 1
    )
    [cap_key] => wp_capabilities
    [roles] => Array (
      [0] => subscriber
    )
    [allcaps] => Array (
      [read] => 1
      [level_0] => 1
      [subscriber] => 1
    )
    [filter] =>
  )
  [1] => WP_User Object ( etc. etc.

Based on this very helpful page on PHP array sorting, I feel like I got something kinda close. Unfortunately, it's just giving me a blank page after the part where the code appears.

          function cmp(array $a, array $b) {
              if ($a['data']['display_name'] < $b['data']['display_name']) {
                  return -1;
              } else if ($a['data']['display_name'] > $b['data']['display_name']) {
                  return 1;
              } else {
                  return 0;
              }
          }

          usort($user_query->results, 'cmp');

Anyone wanna point me towards what I'm doing wrong?

  • 写回答

1条回答 默认 最新

  • douxi3085 2017-05-24 02:08
    关注

    It's because you are trying to access property of object in method of accessing array element. You cannot use the index to access the property of object. You should use -> instead of []. You can check this demo to issustrate how to access object property.

    refer to how to access array/object

    change your $a['data']['display_name'] to $a->data->display_name, and your $b in the compare funciton.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?