2017-10-19 112 views
-2

我是一個小白試圖解決我正在做的單詞搜索應用程序。我的目標是獲取一個字符串,並比較該字符串的每個字母出現在另一個字符串中的次數。然後將該信息放入一個鍵值對的數組中,其中鍵是第一個字符串的每個字母,值是次數。然後用ar(排序)排序並最終回顯出現最多的字母的值(因此具有最高值的鍵)。如何創建並填充一個新的關聯數組,每個數組都創建一個值?

所以它會像array('t'=> 4,'k'=>'9','n'=> 55),回顯'n'的值。謝謝。

這是我到目前爲止是不完整的。

<?php 

     $i = array(); 

     $testString= "endlessstringofletters"; 

     $testStringArray = str_split($testString); 

     $longerTestString= "alphabetalphabbebeetalp 
habetalphabetbealphhabeabetalphabetalphabetalphbebe 
abetalphabetalphabetbetabetalphabebetalphabetalphab 
etalphtalptalphabetalphabetalbephabetalphabetbetetalphabet"; 


      foreach ($testStringArray AS $test) { 

       $value = substr_count($longerTestString, $testStringArray); 

       /* Instead of the results of this echo, I want each $value to be matched with each member of the $testStringArray and stored in an array. */ 
      echo $test. $value;  

     } 
/* I tried something like this outside of the foreach and it didn't work as intended */ 
$i = array_combine($testStringArray , $value); 

      print_r($i); 
+0

我不能完全肯定,如果這是一個確切的重複,但是這讓我想起了很多[這個最近的問題](https://stackoverflow.com/questions/46733941/sorting-characters-by-count-using-php-or-python) –

+1

什麼是$字母?我不能看到它在任何地方聲明 –

+0

https://www.w3schools.com/php/php_arrays.asp會向你展示數組語法,看看關聯數組。這將允許您替換該回聲語句。 – Nic3500

回答

0

如果我理解正確的話,你所追求的,那麼它就是這麼簡單:

<?php 

    $shorterString= "abc"; 

    $longerString= "abccbaabaaacccb"; 

    // Split the short sring into an array of its charachters 
    $stringCharachters = str_split($shorterString); 

    // Array to hold the results 
    $resultsArray = array(); 

    // Loop through every charachter and get their number of occurences 
    foreach ($stringCharachters as $charachter) { 
     $resultsArray[$charachter] = substr_count($longerString,$charachter); 
    } 

    print_r($resultsArray); 
相關問題