Using usort in php to sort an array of objects?

后端 未结 3 1446
無奈伤痛
無奈伤痛 2020-12-21 13:42

I did look at usort, but am still a little confused...

Here is what the $myobject object looks like:

Array
(
    [0] => stdClass Object
                 


        
相关标签:
3条回答
  • 2020-12-21 14:15

    I have been trying to write a comparing function for three hours. It is very easy in fact but I thought I was missing something and wrote it again and again from scratch changing algorithm in many ways testing it with my sample array.

    At last I realized that the problem is at internal uasort function. It does not finish comparing with all items. I don't remember the name of used algorithm right now but I myself use an improved version (ow mine) in C++. The algorithm uses a binary-tree like comparison method by dividing the array into as many pairs as required in a recursive call to the sorting function with new indexes (lower, upper limits) each time.

    When the remaining slice is of one item, then upper and lower indexes are the same and function thinks that it has finished (handled all items) although the last item was not evaluated. Sorting functions using that algorithm fail when the most-inner block has an odd number. It works fine 2, 4, 8 .... elements, but cant work with 3, 5, 7 etc... The exact condition of failure depends on the elements sort order. Numbers may not always be meaningful.

    I solved that problem years ago. I cant solve it by myself for PHP now because I dont have a PHP compiler and I don't have PHP source code either. But if anybody from PHP development team contacts me, I can supply the working copy of that algorithm in C++. The same algorithm is the fastest way of accessing sorted elements.

    0 讨论(0)
  • 2020-12-21 14:18

    cmp is the a callback function that usort uses to compare complex objects (like yours) to figure out how to sort them. modify cmp for your use (or rename it to whatever you wish)

    function cmp( $a, $b )
    { 
      if(  $a->tid ==  $b->tid ){ return 0 ; } 
      return ($a->tid < $b->tid) ? -1 : 1;
    } 
    usort($myobject,'cmp');
    
    function sort_by_tid( $a, $b )
    { 
      if(  $a->tid ==  $b->tid ){ return 0 ; } 
      return ($a->tid < $b->tid) ? -1 : 1;
    } 
    usort($myobject,'sort_by_tid');
    

    http://www.php.net/usort

    0 讨论(0)
  • 2020-12-21 14:28

    For get property stdClass Object use operator ->{'name_property'}, eg $a->{'tid'}

    function cmp( $a, $b )
    { 
      if(  $a->{'tid'} ==  $b->{'tid'} ){ return 0 ; } 
      return ($a->{'tid'} < $b->{'tid'}) ? -1 : 1;
    } 
    usort($myobject,'cmp');
    
    function sort_by_tid( $a, $b )
    { 
      if(  $a->{'tid'} ==  $b->{'tid'} ){ return 0 ; } 
      return ($a->{'tid'} < $b->{'tid'}) ? -1 : 1;
    } 
    usort($myobject,'sort_by_tid');
    
    0 讨论(0)
提交回复
热议问题