问题描述
我有一个函数,可以找到数组的所有可能组合:
I have a function that finds all the possible combinations of an array:
function combination($array)
{
$results = array(array());
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return $results;
}
这将返回一个多维数组,并且可以正常工作.
This returns a multidimensional array and it works.
如果我尝试打印阵列,请使用以下命令:
If I try to print the array, I use this:
foreach (combination($set) as $combination)
{
print join("\t", $combination) . " - ";
}
针对:$set = array('s','f','g');
输出为:- s - f - f s - g - g s - g f - g f s -
现在我不知道的是如何根据长度对组合进行排序,使输出变为:- g f s - g s - g f - f s - g - s - f -
Now what I cant figure out is how can I sort the combinations according to length in a way where the output becomes: - g f s - g s - g f - f s - g - s - f -
推荐答案
您需要为此使用'usort':
you need to use 'usort' for this:
function sortByLength($a, $b) {
return count($b) - count($a);
}
$result = combination($set);
usort($result, 'sortByLength');
如果只使用一次,您也可以仅将'sortByLength'用作匿名函数,而不是对其进行定义:
you could also just use 'sortByLength' as an anonymous function, instead of defining it, if you use this only once:
$result = combination($set);
usort($result, function($a, $b) {
return count($b) - count($a);
} );
这篇关于根据PHP中的长度对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!