PHP usort won't sort class

岁酱吖の 提交于 2019-12-23 06:56:57

问题


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!'


回答1:


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('Full\Namespace\WebPageInformation', 'compare_method'));



回答2:


Also, you can set a static function inside your Class:

static myfunction($a, $b){'yoursort'}

and call it like this:

usort($items, "Class::myfunction");


来源:https://stackoverflow.com/questions/6419818/php-usort-wont-sort-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!