PHP usort 不会对类进行排序

标签 php usort

这是要排序的元素数组的示例:

$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)

那么,假设我想按 brand_id 排序。 这是我的 usort 回调函数:

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...
    }

}

当我执行 usort($items, '_compare'); var_dump($items); 没有任何反应。关于如何解决此问题的任何线索?

--更新--

好的,我把问题简化为:

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

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

它总是打印'无法排序!'

最佳答案

终于找到了这个错误的根源。问题是这段代码在一个类中。

如果是这种情况,那么您应该这样调用 usort:

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

此外,如果您的类在命名空间中,您应该在 usort 中列出完整的命名空间。

usort($items, array('Full\Namespace\WebPageInformation', 'compare_method'));

关于PHP usort 不会对类进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6419818/

相关文章:

php - Strip_tags() 期望参数 1 为字符串,给定数组

php - usort 不适用于 laravel 多维数组

php - 比较 mysql 和 php 中的两个数组

javascript - 禁用 html 中日历 View 的输入类

php - 阻止下一个索引因完整性违规而增加

php - 按修改日期排序这个数组?

PHP -- usort 正在修改数组中对象的内容,我该如何防止这种情况发生?

php - 自动 Paypal 付款

php - 如何按日期字段降序对数组进行排序?

PHP uSort 优化?