Sort array of objects by object fields

后端 未结 19 1558
情书的邮戳
情书的邮戳 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:04

    Thanks for the inspirations, I also had to add an external $translator parameter

    usort($listable_products, function($a, $b) {
        global $translator;
        return strcmp($a->getFullTitle($translator), $b->getFullTitle($translator));
    });
    
    0 讨论(0)
  • 2020-11-22 03:04

    This is what I have for a utility class

    class Util
    {
        public static function sortArrayByName(&$arrayToSort, $meta) {
            usort($arrayToSort, function($a, $b) use ($meta) {
                return strcmp($a[$meta], $b[$meta]);
            });
        }
    }
    

    Call it:

    Util::sortArrayByName($array, "array_property_name");
    
    0 讨论(0)
  • 2020-11-22 03:10
    usort($array, 'my_sort_function');
    
    var_dump($array);
    
    function my_sort_function($a, $b)
    {
        return $a->name < $b->name;
    }
    

    The same code will be with the count field.

    More details about usort: http://ru2.php.net/usort

    Btw, where did you get that array from? I hope that not from database?

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

    You can use usort, like this:

    usort($array,function($first,$second){
        return strcmp($first->name, $second->name);
    });
    
    0 讨论(0)
  • 2020-11-22 03:13

    A simple alternative that allows you to determine dynamically the field on which the sorting is based:

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

    This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.

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

    If you need local based string comparison, you can use strcoll instead of strcmp.

    Remeber to first use setlocale with LC_COLLATE to set locale information if needed.

      usort($your_data,function($a,$b){
        setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
        return strcoll($a->name,$b->name);
      });
    
    0 讨论(0)
提交回复
热议问题