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

时间:2013-07-15 11:44:00

标签: php arrays sorting

假设我有一个这样的数组:

$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(代码)除以-
例如:

$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

目标是对数组进行排序而不会丢失任何长度。

我尝试使用树算法,但我无法使用它。

2 个答案:

答案 0 :(得分:3)

疯狂的做法:

  1. 生成所有可能的排列
  2. 遍历每个排列并查看是否存在多米诺骨牌效应并将其添加到输出
  3. 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 http://stackoverflow.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

答案 1 :(得分:1)

一种蛮力的方式,在PHP中。 (未经测试):

<?php

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

function findMatches($i, $val_ignore, $arr) {
    $arr_matches = array();
    foreach($arr as $key => $val) {
      $j = substr_replace($val, '', 2);
      if (($i == $j) && ($val != $val_ignore))
        $arr_matches[] = $val;
    }
    return $arr_matches;
}

$arr_sorted = array();
foreach($arr as $key => $val) {
    $i = substr_replace($val, '', 0, 3);
    if (!in_array($val, $arr_sorted)) $arr_sorted[] = $val;
    $arr_sorted = array_merge($arr_sorted, findMatches($i, $val, $arr));
}

?>