PHP选择排序的半数字数组实际上没有排序

时间:2018-05-09 00:35:51

标签: php arrays sorting

我在PHP中有一个数组:

==============================================================================
Path                                                                          
==============================================================================
Handle Spaces
C:\Users\eddy.pronk\Library\Application Support\Foo.txt
| PASS |
------------------------------------------------------------------------------
Path                                                                  | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Output:  C:\work\output.xml
Log:     C:\work\log.html
Report:  C:\work\report.html

我希望通过LAST列(Score列)对此数组进行排序。我使用的代码是一个略微修改的选择排序版本,允许我通过提取得分参数并使用该值而不是整个文本进行排序(在这种情况下,您无法按文本排序)。

(Name, level, score)
array(5) { 
    [0]=> string(28) "Mr Kowalchuk,9,4000000000" 
    [1]=> string(12) "Test Boy    ,0,0" 
    [2]=> string(16) "Mr Test     ,2,150" 
    [3]=> string(16) "Rutherford  ,6,490" 
    [4]=> string(18) "Isaac Newton,3,235" 
}

我用

调用我的函数
<?php
function getScoreValue($row) {
    return (int)(explode(",", $row)[2]);
}

function minIndex($ma, $mi, $mj) {
    if ($mi == $mj) {
        return $mi;
    }
    $k = minIndex($ma, $mi + 1, $mj);
    if (getScoreValue($ma[$mi]) < getScoreValue($ma[$k])) {
        return $mi;
    } else {
        return $k;
    }
}

function recursiveSelectionSort($ma, $mn, $mindex = 0) {
    ##echo 'Running...<br>';
    if ($mindex == $mn) {
        return -1;
    }
    $k = minIndex($ma, $mindex, $mn - 1);
    if ($k != $mindex) {
        $temp = $ma[$k];
        $ma[$k] = $ma[$mindex];
        $ma[$mindex] = $temp;
    }
    recursiveSelectionSort($ma, $mn, $mindex + 1);
}

但是,使用PHP的recursiveSelectionSort($myarray, sizeof($mayarry)); ,它表明数组保持不变并且不会更改。知道为什么会这样,我能做些什么来解决它?

1 个答案:

答案 0 :(得分:1)

这里不需要任何递归。这是我的想法。 检查评论以获得解释

$a1=array( 
    "Mr Kowalchuk,9,4000000000", 
    "Test Boy    ,0,0" ,
    "Mr Test     ,2,150", 
    "Rutherford  ,6,490" ,
    "Isaac Newton,3,235" ,
    );

//explode entires with comma to make nested array
$a2=array_map(function ($a) { return explode(",",$a); }, $a1);
//sort based on inner key 
usort($a2, function ($a, $b) { return $a[2] - $b[2]; });
//implode back with comma to make it 1d array
$a3=array_map(function ($a) { return implode(",",$a); }, $a2);
echo "<pre>";
print_r($a3);

输出

Array
(
    [0] => Test Boy    ,0,0
    [1] => Mr Test     ,2,150
    [2] => Isaac Newton,3,235
    [3] => Rutherford  ,6,490
    [4] => Mr Kowalchuk,9,4000000000
)