I want to sort an array by using uasort() function. I wrote this piece of code and it worked well:
function cmp($a, $b)
{
$_a = strlen($a);
$_b = strlen($b);
if($_a==$_b)
{
return 0;
}
return ($_a < $_b)? -1 : +1;
}
$arr = array(
"234560"=>"the quick brown fox jump",
"234561"=>"the quick brown fox jump over the lazy dog",
"234562"=>"the quick brown"
);
$array = uasort($arr,"cmp");
But when I put it in a class, it return null with a warning:
Warning: uasort() expects parameter 2 to be a valid callback, function 'cmp' not found or invalid function name in...
Here is my code
class Zend_Controller_Action_Helper_Utility extends Zend_Controller_Action_Helper_Abstract
{
public function uasort($array)
{
return uasort($array, "cmp");
}
function cmp($a, $b)
{
$_a = strlen($a);
$_b = strlen($b);
if ($_a == $_b)
{
return 0;
}
return ($_a < $_b) ? -1 : +1;
}
}
I also try
return uasort($array, "Zend_Controller_Action_Helper_Utility::cmp");
with static function cmp(){}
but I still return null.
How can I fix it?
You are specifying the callback wrong. If it is an instance method, you need to specify it as
array($this, 'cmp');
If you make it a static method, you need to specify it as
array('Zend_Controller_Action_Helper_Utility', 'cmp');
See the documentation of callback for more details.