dongzouxigu12345 2009-08-04 19:05
浏览 84
已采纳

PHP“警告:usort()[function.usort]:排序时无效的比较函数”

i have following data as an associative array

array
  'abc' => 
    array
      'label' => string 'abc' (length=3)
      'weight' => float 3
  'wsx' => 
    array
      'label' => string 'wsx' (length=3)
      'weight' => float 1
  'qay' => 
    array
      'label' => string 'qay' (length=3)
      'weight' => float 1
  'http://test.com' => 
    array
      'label' => string 'http://test.com' (length=15)
      'weight' => float 0
  'Nasi1' => 
    array
      'label' => string 'Nasi1' (length=5)
      'weight' => float 0
  'fax' => 
    array
      'label' => string 'fax' (length=3)
      'weight' => float 4

I want to sort the array using "label" or "weight"

The compare function for the label is:

function compare_label($a, $b)
{
    return strnatcmp($a['label'], $b['label']);
}

and than i just call the function from another function:

usort($label, 'compare_label');
var_dump($label);

but then i get the error message and the array is not sorted. I don't know, what I'm doing wrong. I've tried to replace:

  • usort($label, 'compare_label'); with usort($label, compare_label);
  • usort($label, 'compare_label'); with usort($label, $this->compare_label);

without success. Can someone give me a hint?

  • 写回答

2条回答 默认 最新

  • doz97171 2009-08-04 19:15
    关注

    if compare_label is a member function (i.e., class method) then you need to pass it differently.

    usort( $label, array( $this, 'compare_label' ) );
    

    Basically, instead of just sending a string of the function name, you send an two-element array, where the first element is the context (object on which the method can be found), and the 2nd element is the string of the function name.

    NOTE: If your method is static, then you pass the class name as the first element of the array

    usort( $label, array( __CLASS__, 'compare_label' ) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集