PHP usort won't sort class

Viewed 12050

This is a sample of the array of elemnts to sort:

$items = 
    array
      0 => 
        object(stdClass)[8]
          public 'id' => string '110' (length=3)
          public 'brand_id' => string '18' (length=2)
            array
              0 => string ' OT-708' (length=7)
          public 'failed' => null
          public 'diff' => null
      1 => 
        object(stdClass)[9]
          public 'id' => string '161' (length=3)
          public 'brand_id' => string '18' (length=2)

So, let's say I want to sort by brand_id. This is my usort callback function:

function _compare($itemA, $itemB){

    if ($itemA->brand_id == $itemB->brand_id) {

        return 0; 
    }
    else{
        return strcmp($itemA->brand_id, $itemB->brand_id); //just an example...
    }

}

And when I do usort($items, '_compare'); var_dump($items); nothing happens. Any clues on how to troubleshoot this?

--UPDATE--

Ok, I've simplified the problem to this:

function cmp($itemA, $itemB){
    return -1;
}

if (usort($items, "cmp"))
                echo 'I just sorted!';
else echo 'Cant sort!';

It always prints 'Cant sort!'

3 Answers

You can also use $this if you use usort in a Class:

usort($my_array, array($this, 'orderByDate'));
Related