0

我从一个文本文件中读取了一些单词,使用 file() 函数将每个单词存储为一个数组元素。现在我需要对每个单词进行排序并创建一个关联数组,将排序后的字符串存储为键,将原始字符串存储为值,如下所示:

$hash_table = array( 'sorted_string' => 'original string' );

我遍历从文件中读取的每个单词并按升序对其进行排序,但是当将其推送到关联数组时,我完全迷失了。谁能告诉我如何创建关联数组?

4

3 回答 3

3
$a = array('green', 'yellow', 'red');//actual
$b = array('green', 'yellow', 'red');
sort($b); //sorted
$c = array_combine($b, $a);
于 2013-06-17T11:56:17.913 回答
1

如果我正确理解您的问题,请考虑以下问题:

$sorted;   //sorted array
$original; //original array

foreach($sorted as $key){
  $index = 0;
  $new_array[$key] = $original[$index++];
}
于 2013-06-17T11:46:20.703 回答
0

这是你想要的:

<?php
//create an array with words, similar to what you get with file()
$str = "here is a list of random words that will be sorted";
$array = explode(" ", $str);

//a place to store the result
$result = array();

//check each value
foreach($array as $word) {
  //str_split will create an array from a string
  $letters = str_split(trim($word));
  //sort the letters
  sort($letters);

  //implode the letters again to a single word
  $sorted = implode($letters);

  //add to result
  $result[$sorted] = $word;
}

//dump
var_dump($result);

//sort on the key
ksort($result);

//dump
var_dump($result);
?>

这将输出

//unsorted
array(11) {
  ["eehr"]=>
  string(4) "here"
  ["is"]=>
  string(2) "is"
  ["a"]=>
  string(1) "a"
  ["ilst"]=>
  string(4) "list"
  ["fo"]=>
  string(2) "of"
  ["admnor"]=>
  string(6) "random"
  ["dorsw"]=>
  string(5) "words"
  ["ahtt"]=>
  string(4) "that"
  ["illw"]=>
  string(4) "will"
  ["be"]=>
  string(2) "be"
  ["deorst"]=>
  string(6) "sorted"
}

//sorted on key
array(11) {
  ["a"]=>
  string(1) "a"
  ["admnor"]=>
  string(6) "random"
  ["ahtt"]=>
  string(4) "that"
  ["be"]=>
  string(2) "be"
  ["deorst"]=>
  string(6) "sorted"
  ["dorsw"]=>
  string(5) "words"
  ["eehr"]=>
  string(4) "here"
  ["fo"]=>
  string(2) "of"
  ["illw"]=>
  string(4) "will"
  ["ilst"]=>
  string(4) "list"
  ["is"]=>
  string(2) "is"
}
于 2013-06-18T06:48:57.177 回答