我有以下数据作为关联数组
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_label);但没有成功。谁能给我个提示吗?
发布于 2009-08-04 19:15:24
如果compare_label是一个成员函数(即类方法),那么需要以不同的方式传递它。
usort( $label, array( $this, 'compare_label' ) );基本上,不只是发送函数名的字符串,而是发送一个双元素数组,其中第一个元素是上下文(可以在其中找到方法的对象),第二个元素是函数名的字符串。
注意:如果方法是静态的,则将类名作为数组的第一个元素传递。
usort( $label, array( __CLASS__, 'compare_label' ) );发布于 2009-08-04 19:17:14
比较函数是定义为全局函数还是对象的方法?如果它是一种方法,那么您必须稍微更改一下它的名称:
usort($label, array($object, "compare_label")); 您还可以将其声明为类本身的静态方法:
public static function compare_label ($a, $b) {
[...]
}
usort($label, array(Class_Name, "compare_label"));https://stackoverflow.com/questions/1229324
复制相似问题