簡體   English   中英

用字符串創建一個關聯數組

[英]Creating an associative array with strings

我從文本文件中讀取了一些單詞,並使用file()函數將每個單詞存儲為數組元素。 現在,我需要對每個單詞進行排序,並創建一個關聯數組,將排序后的字符串存儲為鍵,將原始字符串存儲為值,如下所示:

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

我遍歷從文件中讀取的每個單詞,並按升序對其進行排序,但是當將其推入關聯數組時,我完全迷失了。 誰能告訴我如何創建關聯數組?

$a = array('green', 'yellow', 'red');//actual
$b = array('green', 'yellow', 'red');
sort($b); //sorted
$c = array_combine($b, $a);

如果我正確理解您的問題,請考慮以下問題:

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

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

這是您想要的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM