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


How to alphabetize from a random alphabet in PHP

我的任务是在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";
}
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 应为字符串。请注意,我总是对返回 <0 还是返回>0 进行排序方向感到困惑;您可能需要交换$a并在某个地方$b