Using usort in php to sort an array of objects?

11,226

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

Share:
11,226
andy787899
Author by

andy787899

Updated on June 04, 2022

Comments

  • andy787899
    andy787899 almost 2 years

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

    Here is what the $myobject object looks like:

    Array
    (
        [0] => stdClass Object
            (
                [tid] => 13
                [vid] => 4
            )
    
        [1] => stdClass Object
            (
                [tid] => 10
                [vid] => 4
            )
    
        [2] => stdClass Object
            (
                [tid] => 34
                [vid] => 4
            )
    
        [3] => stdClass Object
            (
                [tid] => 9
                [vid] => 4
            )
    

    I saw this:

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

    I'm trying to sort according to tid, but, I guess I'm just not sure really if I have to change weight to something? Or will it just work as is? I tried it, but nothing outputted...

  • andy787899
    andy787899 about 14 years
    Ok, thanks for explaining that, but it's still not working... Am I not allowed to assign that to a variable or something? Because when I do $myobject = usort($myobject, 'cmp'), it doesn't output anything at all? I'm assuming I just need one or the other functions from above, and not both, since they both do the same thing?
  • andy787899
    andy787899 about 14 years
    Also, I did also try renaming the two variables to $myobject1 and $myobject2 = usort... but that didn't work either...
  • andy787899
    andy787899 about 14 years
    Nevermind! Should have just tried not assigning it before posting... thanks!
  • scootklein
    scootklein about 14 years
    usort is one of the few php functions that takes a pointer as an input (very C-ish in style) and returns a boolean. check out the PHP documentation page. try just putting usort($myobject, 'cmp') and then checking what $myobject has.