Using usort in php to sort an array of objects?

后端 未结 3 1445
無奈伤痛
無奈伤痛 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: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');
    

提交回复
热议问题