gpt4 book ai didi

php - usort - 更多参数

转载 作者:行者123 更新时间:2023-12-04 06:56:47 28 4
gpt4 key购买 nike

您好,如何向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);
?>

最佳答案

您可以使用更简单的函数:

function sortNumberAsc($a, $ b){
$a = $a['number'];
$b = $ b['number'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : +1;
}

关于php - usort - 更多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2472809/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com