【问题标题】:Sorting a multi-dimensional array according to length in PHP在PHP中根据长度对多维数组进行排序
【发布时间】:2012-06-01 15:16:38
【问题描述】:

我有一个函数可以找到数组的所有可能组合:

function combination($array) 
{    
    $results = array(array());

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return $results;
}

这会返回一个多维数组并且它可以工作。

如果我尝试打印数组,我会使用这个:

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 -

【问题讨论】:

标签: php sorting


【解决方案1】:

您需要为此使用“usort”:

function sortByLength($a, $b) {
    return count($b) - count($a);
}

$result = combination($set);

usort($result, 'sortByLength');

如果你只使用一次,你也可以只使用 'sortByLength' 作为匿名函数,而不是定义它:

$result = combination($set);

usort($result, function($a, $b) {
    return count($b) - count($a);
} );

【讨论】:

  • 没错,但我不是要对 $set 进行排序,而是要对组合($set)进行排序。
  • 只需将组合($set)的结果保存在变量中 - 我为您编辑了示例
  • 您的脚本使用一维数组,combination($set) 是一个多维数组
  • 能贴出多维数组的数组结构吗?排序后的数组必须保持多维还是一维?
  • 为此,您基本上只需将 strlen() 更改为 count() - 它甚至可以保持多维状态。我会编辑它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
相关资源
最近更新 更多