如何在PHP中从随机字母表中按字母顺序排列

时间:2015-01-29 18:50:23

标签: php sorting

我的任务是按字母顺序在php中对单词列表进行排序。我遇到的问题是我排序的字母表不是标准的英文字母。它是26个字母的随机排序,我已经存储在一个数组中。我正在考虑使用usort,但我不确定如何编写使用随机字母表的比较器函数。

这是我到目前为止所拥有的

// read in from file
$inFile = fopen($argv[1], "r");
$newOrder = trim(fgets($inFile));
$numWords = fgets($inFile);
$wordList = array();
$i = 0;
// put word list into an array
while(!feof($inFile)){
  $wordList[$i] = fgets($inFile);
  $i++;
}
// split new order into array
$newOrder = explode(" ", $newOrder);
$lastI = count($wordList) - 1;
unset($wordList[$lastI]);
print_r($newOrder);


// write comparator function
function cmpByNewOrder($a, $b){
  global $newOrder;
  $correctOrder = $newOrder;
  $aKey = array_search($a, $correctOrder);
  $bKey = array_search($b, $correctOrder);
  if ($aKey == $bKey){
    return 0;
  }
  return ($aKey < $bKey) ? -1 : 1;
}


print "Original List\n";
for ($i = 0; $i < count($wordList); $i++){
  print trim($wordList[$i]) . "\n";
}
print "\n";

usort($wordList, "cmpByNewOrder");

print "Sorted List\n";
for ($i = 0; $i < count($wordList); $i++){
  print trim($wordList[$i]) . "\n";
}

1 个答案:

答案 0 :(得分:0)

usort($words, function ($a, $b) /* use ($order) */ {
    // statically initialising custom order; static because of efficiency
    // alternatively, import from outer scope via use() above
    static $order = null;
    if (!$order) {
        $order = array_flip(['f', 'b', 'x', 'i', ...]);
    }

    // iterate every letter in both strings
    for ($i = 0, $length = min(strlen($a), strlen($b)); $i < $length; $i++) {
        // compare the order
        if ($diff = $order[$a[$i]] - $order[$b[$i]]) {
            // if there's a difference, return it
            return $diff;
        }
    }

    // both strings were equal so far, let's decide on length
    return strlen($a) - strlen($b);
});

$a$b应该是字符串。请注意,我总是混淆是否返回&lt; 0或&gt; 0的排序方向;您可能需要在某处交换$a$b