Sort multi-dimensional array by specific key

后端 未结 5 2098
你的背包
你的背包 2020-11-28 15:51

I have an array:

Array (
    [0] => stdClass Object (
        [user_id] => 1
        [ID] => 1
        [user_login] => admin
        [display_nam         


        
相关标签:
5条回答
  • 2020-11-28 16:08

    See usort: http://php.net/manual/en/function.usort.php

    usort($array, "my_cmp");
    
    function my_cmp($a, $b) {
      if ($a->display_name == $b->display_name) {
        return 0;
      }
      return ($a->display_name < $b->display_name) ? -1 : 1;
    }
    
    0 讨论(0)
  • 2020-11-28 16:09

    I have find answer at https://joshtronic.com/2013/09/23/sorting-associative-array-specific-key/

    function sortBy($field, &$array, $direction = 'asc')
    {
        usort($array, create_function('$a, $b', '
            $a = $a["' . $field . '"];
            $b = $b["' . $field . '"];
    
            if ($a == $b)
            {
                return 0;
            }
    
            return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
        '));
    
        return true;
    }
    

    And now call this function by specific array key.

    $newArray = sortBy('display_name',   $blogusers);
    

    And if sort in asc/desc just add one argument,

    sortBy('display_name',   $blogusers, 'desc');
    
    0 讨论(0)
  • 2020-11-28 16:20

    Take a look at following article. It does describe how to use usort() and also describes how to use create_function() so that you can use single function to sort on different fields (with required direction asc or desc).

    http://phpave.com/sorting-associative-array-specific-key/

    0 讨论(0)
  • 2020-11-28 16:26

    Your array looks like the result of a database query. If this is a case, let the database do the sorting: just append ORDER BY display_name to the query.

    0 讨论(0)
  • 2020-11-28 16:28

    You would use usort() - http://php.net/usort

    My suggestion would be:

        function cmp($a, $b)
        {
            return strcmp($a->display_name, $b->display_name);
        }
    
        usort($blogusers, "cmp");
    
        foreach ($blogusers as $bloguser)
        {
            ...
    
    0 讨论(0)
提交回复
热议问题