【问题标题】:Creating an associative array with strings使用字符串创建关联数组
【发布时间】:2013-06-13 08:34:10
【问题描述】:

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

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

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

【问题讨论】:

  • 语法很简单:$hash_table["key"] = "value";
  • 如何对单个单词进行排序?你想让字母切换位置按字母顺序排列吗?
  • 所以“正确”会被排序为“ceorrtC”?
  • @MayankKumar 请发布您用来生成关联数组的代码,这样我们就可以“修复”您出错的地方。
  • @HugoDelsing:没错。这就是我正在做的事情。

标签: php hashtable associative-array


【解决方案1】:

如果我理解你的问题,请考虑一下:

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

foreach($sorted as $key){
  $index = 0;
  $new_array[$key] = $original[$index++];
}

【讨论】:

  • 好,不确定这是否是 OP 需要的,因为这将提供一个多维数组($original 是一个数组)。
  • @HamZa 我认为,现在编辑的答案将至少接近回答 OP 的问题。
  • 是的,你得到了我的 +1 :)
  • @HamZa 我认为您应该 +1 其他答案。 :)
  • 我做到了,这有点令人难过,因为如果 OP 回答了我的问题(在 cmets 中),我将准确地发布该答案:p
【解决方案2】:
$a = array('green', 'yellow', 'red');//actual
$b = array('green', 'yellow', 'red');
sort($b); //sorted
$c = array_combine($b, $a);

【讨论】:

    【解决方案3】:

    这是你想要的:

    <?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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多