如何使用PHP对数组进行排序

说我有一个像这样的数组:

$arr_sequences = 
    array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');

如何对数组进行排序,以使值看起来像这样:

$arr_sequences = 
    array('00-02', '02-03', '03-23', '23-03', '03-07', '07-11', '11-11', '11-10');

如果仔细观察,则每个值都有一个ID(代码),该ID除以-
例如 :

$arr_sequences[2] = '03-07'; // '07' as last code, then search another value with '07' in front of the value

那么下一个指标值应该是

$arr_sequences[5] = '07-11'; // '07' front, then search '11' as next value

目标是在不丢失任何长度的情况下对数组进行排序.

我已经尝试过使用树算法,但是无法正常工作.

解决方法:

疯狂的做法:

>生成所有可能的排列
>遍历每个排列,看看是否有多米诺骨牌效应并将其添加到输出中

PHP代码

$arr_sequences = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11'); // Input

$permutations = permutations($arr_sequences); // Generating permutations

// Generating a regex
$n = count($arr_sequences);
$regex = '\d+';
for($i=1;$i<$n;$i++){
    $regex .= '-(\d+)-\\'.$i;
}
$regex .= '-\d+';

$sorted = preg_grep('#'.$regex.'#', $permutations); // Filtering the permutations
sort($sorted); // re-index the keys

//generating the desired output
$output = array();
foreach($sorted as $key => $sample){
    $temp = explode('-', $sample);
    $c = count($temp); // Micro-optimization, yeaaaah!
    for($i=0;$i<$c;$i+=2){
        $output[$key][] = $temp[$i] . '-' . $temp[$i+1];
    }
}

print_r($output); // printing

// Function from https://*.com/a/14998162
function permutations($elements) {
    if(count($elements)<2) return $elements;
    $newperms= array();
    foreach($elements as $key=>$element) {
        $newelements= $elements;
        unset($newelements[$key]);

        $perms= permutations($newelements);
        foreach($perms as $perm) {
            $newperms[]= $element."-".$perm;
        }
    }
    return $newperms;
}

输出

Array
(
    [0] => Array
        (
            [0] => 00-02
            [1] => 02-03
            [2] => 03-23
            [3] => 23-03
            [4] => 03-07
            [5] => 07-11
            [6] => 11-11
            [7] => 11-10
        )

)

似乎只有一种解决方案:p

上一篇:JavaScript,array.sort()仅基于其中一个的两个数组


下一篇:Linux AWK排序降序不起作用