Skip to content
Advertisement

PHP usort won’t sort class

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!

Advertisement

Answer

Finally, I discovered the source of this error. The problem was that this code was inside a class.

If that’s your case, then you should call usort this way:

usort($items, array("MyClass", "compare_method"));

Furthermore, if your Class is in a namespace, you should list the full namespace in usort.

usort($items, array('FullNamespaceWebPageInformation', 'compare_method'));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement