[英]Sorting a multi-dimensional array according to length in PHP
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) . " - ";
}
For: $set = array('s','f','g');
对于:
$set = array('s','f','g');
The output is: - s - f - fs - g - gs - gf - gfs -
输出是:
- s - f - fs - g - gs - gf - gfs -
Now what I cant figure out is how can I sort the combinations according to length in a way where the output becomes: - gfs - gs - gf - fs - g - s - f -
现在我无法弄清楚如何根据长度以输出变为的方式对组合进行排序:
- gfs - gs - gf - fs - g - s - f -
you need to use 'usort' for this: 你需要使用'usort'来做到这一点:
function sortByLength($a, $b) {
return count($b) - count($a);
}
$result = combination($set);
usort($result, 'sortByLength');
you could also just use 'sortByLength' as an anonymous function, instead of defining it, if you use this only once: 您也可以使用'sortByLength'作为匿名函数,而不是定义它,如果您只使用一次:
$result = combination($set);
usort($result, function($a, $b) {
return count($b) - count($a);
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.