PHP“;警告:usort()[function.usort]:无效的比较函数;论分类

PHP“;警告:usort()[function.usort]:无效的比较函数;论分类,php,sorting,associative-array,warnings,Php,Sorting,Associative Array,Warnings,我将以下数据作为关联数组 array 'abc' => array 'label' => string 'abc' (length=3) 'weight' => float 3 'wsx' => array 'label' => string 'wsx' (length=3) 'weight' => float 1 'qay' => array 'lab

我将以下数据作为关联数组

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
我想使用“标签”或“重量”对数组进行排序

标签的比较功能是:

function compare_label($a, $b)
{
    return strnatcmp($a['label'], $b['label']);
}
然后我从另一个函数调用该函数:

usort($label, 'compare_label');
var_dump($label);
但是我得到了错误消息,数组没有排序。我不知道,我做错了什么。我试图替换:

  • usort($label,'compare_label')带有
    usort($label,compare_label)
  • usort($label,'compare_label')
    usort($label,$this->比较标签)

没有成功。有人能给我一个提示吗?

如果
compare\u label
是一个成员函数(即类方法),那么您需要以不同的方式传递它

usort( $label, array( $this, 'compare_label' ) );
基本上,不只是发送函数名的字符串,而是发送两个元素的数组,其中第一个元素是上下文(可以找到方法的对象),第二个元素是函数名的字符串

注意:如果方法是静态的,则将类名作为数组的第一个元素传递

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

比较函数是定义为全局函数还是对象的方法?如果它是一个方法,您必须稍微更改调用它的方式:

usort($label, array($object, "compare_label")); 
您还可以将其声明为类本身的静态方法:

public static function compare_label ($a, $b) {
   [...]
}

usort($label, array(Class_Name, "compare_label"));