usort - 更多参数
你好,我如何向 usort 传递更多参数? 我有不同的功能,它们在结构上非常相似,我只想有一个功能:
<?php
$arr = array( array('number' => 100, 'string'=>'aaa'),
array('number'=>50, 'string'=>'bdef'),
array('number'=>150, 'string'=>'cbba')
);
usort($arr, 'sortNumberDesc');
//How can I use just a single function?
//How can I pass further parameters to usort?
function sortNumberDesc($a, $b){
$a = $a['number'];
$b = $b['number'];
if ($a == $b) return 0;
return ($a > $b) ? -1 : +1;
}
function sortNumberAsc($a, $b){
$a = $a['number'];
$b = $b['number'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : +1;
}
//I want to do the same with just one function:
//Sort ID is the search index, reverse DESC or ASC
function sort($a, $b, $sortId='number', $reverse = 0){
$a = $a[$sortId];
$b = $b[$sortId];
if ($a == $b) return 0;
if($reverse == false) return ($a > $b) ? -1 : +1;
else return ($a < $b) ? -1 : +1;
}
print_r($arr);
?>
Hallo, how can I pass more parameters to usort?
I have different functions, which are very similar in structure, I want to have just one function:
<?php
$arr = array( array('number' => 100, 'string'=>'aaa'),
array('number'=>50, 'string'=>'bdef'),
array('number'=>150, 'string'=>'cbba')
);
usort($arr, 'sortNumberDesc');
//How can I use just a single function?
//How can I pass further parameters to usort?
function sortNumberDesc($a, $b){
$a = $a['number'];
$b = $b['number'];
if ($a == $b) return 0;
return ($a > $b) ? -1 : +1;
}
function sortNumberAsc($a, $b){
$a = $a['number'];
$b = $b['number'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : +1;
}
//I want to do the same with just one function:
//Sort ID is the search index, reverse DESC or ASC
function sort($a, $b, $sortId='number', $reverse = 0){
$a = $a[$sortId];
$b = $b[$sortId];
if ($a == $b) return 0;
if($reverse == false) return ($a > $b) ? -1 : +1;
else return ($a < $b) ? -1 : +1;
}
print_r($arr);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用更简单的函数:
You can use a much simpler function: