Sort array of objects by object fields

后端 未结 19 1549
情书的邮戳
情书的邮戳 2020-11-22 02:28

How can I sort this array of objects by one of its fields, like name or count ?

  Array
(
    [0] => stdClass Object
        (
          


        
相关标签:
19条回答
  • 2020-11-22 02:57

    Heres a nicer way using closures

    usort($your_data, function($a, $b)
    {
        return strcmp($a->name, $b->name);
    });
    

    Please note this is not in PHP's documentation but if you using 5.3+ closures are supported where callable arguments can be provided.

    0 讨论(0)
  • 2020-11-22 02:58

    Use usort, here's an example adapted from the manual:

    function cmp($a, $b) {
        return strcmp($a->name, $b->name);
    }
    
    usort($your_data, "cmp");
    

    You can also use any callable as the second argument. Here are some examples:

    • Using anonymous functions (from PHP 5.3)

        usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
      
    • From inside a class

        usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
      
    • Using arrow functions (from PHP 7.4)

        usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
      

    Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.

    0 讨论(0)
  • 2020-11-22 02:59

    You can use this function (works in PHP Version >= 5.3):

    function sortArrayByKey(&$array,$key,$string = false,$asc = true){
        if($string){
            usort($array,function ($a, $b) use(&$key,&$asc)
            {
                if($asc)    return strcmp(strtolower($a{$key}), strtolower($b{$key}));
                else        return strcmp(strtolower($b{$key}), strtolower($a{$key}));
            });
        }else{
            usort($array,function ($a, $b) use(&$key,&$asc)
            {
                if($a[$key] == $b{$key}){return 0;}
                if($asc) return ($a{$key} < $b{$key}) ? -1 : 1;
                else     return ($a{$key} > $b{$key}) ? -1 : 1;
    
            });
        }
    }
    

    Example:

    sortArrayByKey($yourArray,"name",true); //String sort (ascending order)
    sortArrayByKey($yourArray,"name",true,false); //String sort (descending order)
    sortArrayByKey($yourArray,"id"); //number sort (ascending order)
    sortArrayByKey($yourArray,"count",false,false); //number sort (descending order)
    
    0 讨论(0)
  • 2020-11-22 03:01

    reference answer of Demodave to eating multi key

     function array_sort_by(array $arr, $keys){
    
        if(!is_array($keys))
            $keyList = explode(',', $keys);
        $keyList = array_keys(array_flip($keyList)); // array_unique 
        $keyList = array_reverse($keyList);
    
        $result = &$arr;
        foreach ($keyList as $key) {
            if(array_key_exists($key, $arr))
                $result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
        }
        return $result;
    }
    
    0 讨论(0)
  • 2020-11-22 03:02

    if you want to sort dates

       usort($threads,function($first,$second){
            return strtotime($first->dateandtime) < strtotime($second->dateandtime);
        });
    
    0 讨论(0)
  • 2020-11-22 03:03

    If you want to sort integer values:

    // Desc sort
    usort($array,function($first,$second){
        return $first->number < $second->number;
    });
    
    // Asc sort
    usort($array,function($first,$second){
        return $first->number > $second->number;
    });
    

    UPDATED with the string don't forget to convert to the same register (upper or lower)

    // Desc sort
    usort($array,function($first,$second){
        return strtolower($first->text) < strtolower($second->text);
    });
    
    // Asc sort
    usort($array,function($first,$second){
        return strtolower($first->text) > strtolower($second->text);
    });
    
    0 讨论(0)
提交回复
热议问题