Sort array of objects by object fields

后端 未结 19 1582
情书的邮戳
情书的邮戳 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 03:15

    If you are using this inside Codeigniter, you can use the methods:

    usort($jobs, array($this->job_model, "sortJobs"));  // function inside Model
    usort($jobs, array($this, "sortJobs")); // Written inside Controller.
    

    @rmooney thank you for the suggestion. It really helps me.

    0 讨论(0)
  • 2020-11-22 03:17

    If you need to sort by only one field, then usort is a good choice. However, the solution quickly becomes messy if you need to sort by multiple fields. In this case, YaLinqo library* can be used, which implements SQL-like query syntax for arrays and objects. It has a pretty syntax for all cases:

    $sortedByName         = from($objects)->orderBy('$v->name');
    $sortedByCount        = from($objects)->orderBy('$v->count');
    $sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
    

    Here, '$v->count' is a shorthand for function ($v) { return $v->count; } (either can be used). These method chains return iterators, but you can get arrays by adding ->toArray() in the end if you need it.

    * developed by me

    0 讨论(0)
  • 2020-11-22 03:20

    Downside of all answers here is that they use static field names, so I wrote an adjusted version in OOP style. Assumed you are using getter methods you could directly use this Class and use the field name as parameter. Probably someone find it useful.

    class CustomSort{
    
        public $field = '';
    
        public function cmp($a, $b)
        {
            /**
             * field for order is in a class variable $field
             * using getter function with naming convention getVariable() we set first letter to uppercase
             * we use variable variable names - $a->{'varName'} would directly access a field
             */
            return strcmp($a->{'get'.ucfirst($this->field)}(), $b->{'get'.ucfirst($this->field)}());
        }
    
        public function sortObjectArrayByField($array, $field)
        {
            $this->field = $field;
            usort($array, array("Your\Namespace\CustomSort", "cmp"));;
            return $array;
        }
    } 
    
    0 讨论(0)
  • 2020-11-22 03:20

    You can use usort like this

    If you want to sort by number:

    function cmp($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, "cmp");
    

    Or Abc char:

    function cmp($a, $b)
    {
        return strcmp($a["fruit"], $b["fruit"]);
    }
    
    $fruits[0]["fruit"] = "lemons";
    $fruits[1]["fruit"] = "apples";
    $fruits[2]["fruit"] = "grapes";
    
    usort($fruits, "cmp");
    

    See more: https://www.php.net/manual/en/function.usort.php

    0 讨论(0)
  • 2020-11-22 03:21

    if you're using php oop you might need to change to:

    public static function cmp($a, $b) 
    {
        return strcmp($a->name, $b->name);
    }
    
    //in this case FUNCTION_NAME would be cmp
    usort($your_data, array('YOUR_CLASS_NAME','FUNCTION_NAME')); 
    
    0 讨论(0)
  • 2020-11-22 03:21

    If everything fails here is another solution:

    $names = array(); 
    foreach ($my_array as $my_object) {
        $names[] = $my_object->name; //any object field
    }
    
    array_multisort($names, SORT_ASC, $my_array);
    
    return $my_array;
    
    0 讨论(0)
提交回复
热议问题