类中的usort函数 [英] usort function in a class
问题描述
我有一个函数可以对多维数组中的数据进行排序,如下所示:
I have a function which sorts data in a multidimensional array, as shown below:
<?php
$data = array();
$data[] = array("name" => "James");
$data[] = array("name" => "andrew");
$data[] = array("name" => "Fred");
function cmp($a, $b)
{
return strcasecmp($a["name"], $b["name"]);
}
usort($data, "cmp");
var_dump($data);
?>
当我运行它时,它按预期工作,按名称返回的数据按升序返回.但是,我需要在课堂上使用它.
When i run this, it works as expected, returning the data ordered by name, ascending. However, I need to use this in a class.
<?php
class myClass
{
function getData()
{
// gets all data
$this -> changeOrder($data);
}
function changeOrder(&$data)
{
usort($data, "order_new");
}
function order_new($a, $b)
{
return strcasecmp($a["name"], $b["name"]);
}
}
?>
使用此方法时,会收到以下警告:警告:usort()期望参数2为有效的回调,未找到函数'order_new'或无效的函数名称.
When I use this, i get the following warning: Warning: usort() expects parameter 2 to be a valid callback, function 'order_new' not found or invalid function name.
当我将order_new函数放到changeOrder函数中时,它可以正常工作,但是我遇到了致命错误:无法重新声明order_new()的问题,所以我不能使用它.有什么建议吗?
When i put the order_new function in the changeOrder function it works fine, but I have problems with Fatal error: Cannot redeclare order_new(), so i cannot use that. Any suggestions?
推荐答案
order_new是一个类方法,而不是全局函数. 正如 PHP手册建议您在这种情况下可以使用
order_new is a class method not a global function. As the PHP-Manual suggest you can use in this case
usort($data, array($this, "order_new"));
或声明order_new static并使用
or declare order_new static and use
usort($data, array("myClass", "order_new"));
这篇关于类中的usort函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!