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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog