2017-03-03 132 views
0

我在PHP中有一個奇怪的問題。我有一個數組中有一些整數值。當我嘗試將數組中的值與目標整數進行比較時,索引不能與數組一起使用,也不能遞增。這是一個例子。數組中沒有提取正確元素的索引| PHP

的問題在於,如果(附加$ J == $ indexOfExposed [$ K])

/* This is a simple function to show some letters of a patient name, while the rest of letters are replaced with asterisks. 
    @Param: Patient name 
    @Return: limited preview of patient name; 
*/ 
function encodeName($name){ 

    $len = strlen($name);      // This is the lenghth of $name. used to itterate and set a range. 
    $numOfExposedLetters = rand(1, 4);   // Random value assigned to see how many letters of the name will be exposed. 
    $indexOfExposed = array();     // This is an array of indexes for exposed letters. 
    $k = 0;          // This counter is used to traverse the $indexOfExposed array. 
    $encodedName = "";       // This is the value we will return after it is generated. 
    $previous = 0;        // Used to keep track of previous value in the $indexOfExposed array. This is incase we have repeated values in the array; 

    /* This loop is used to append random values to the arary of indexes, 
     With $numOfExposedLetters being the quantity of exposed letters. */ 
    for($i = 0; $i < $numOfExposedLetters; $i++){ 
     $indexOfExposed[$i] = rand(2, $len); 
    } 
    sort($indexOfExposed);      // Sort the array, for easier access. 


    /* Ecoding name */ 
    for($j = 1; $j <= $len; $j++){ 

     if($indexOfExposed[$k] == $previous){ 
      $encodedName .= "*"; 
      $k++; 
      continue; 
     } 

     if($j == $indexOfExposed[$k]){ 
      $encodedName .= $name[$j-1]; 
      $previous = $indexOfExposed[$k]; 
      $k++; 
     } 

     else 
      $encodedName .= "*"; 
      $k++; 

    } // end of encode 

    return $encodedName; 

} 

此代碼發生在一個人的名字,並用星號名稱替換字母。隨機索引,並顯示名稱中的實際字母。

+2

如果($ indexOfExposed [$ K] = $以前){那不是一個比較,它的平等,使用==,學會調試... –

+0

嗨,老兄,放鬆一下。這不像你從來沒有錯過一個額外的等號哈哈。感謝您的收穫!可能發生在我正在調試並意外刪除額外= –

+1

@RicardoOrtegaMagaña此錯誤一天發生幾十次,習慣了它。禮貌地指出錯誤,將錯誤標記爲錯字,然後繼續。 – Barmar

回答

2

調試你的代碼是一件單調乏味的工作,不值得。我建議你一個替代實現,希望能夠使用你心中的算法,更容易閱讀和理解,並且運行速度可能更快。

function encodeName($name) 
{ 
    $len = strlen($name); 
    $numOfExposedLetters = rand(1, 4); 
    $encodedName = str_repeat('*', $len); 
    while ($numOfExposedLetters --) { 
     $index = rand(2, $len - 1); 
     $encodedName[$index] = $name[$index]; 
    } 

    return $encodedName; 
} 
+0

美麗的代碼。感謝您的執行。我仍然會嘗試去調試我以前的代碼,這樣我就可以保持我的理智。但我一定會使用你的實現版本。 –

+0

這不保證暴露'$ numOfExposedLetters'字母。隨機索引始終相同時,只顯示一個字母。 –

+0

是的,但這沒關係。我只需要揭穿這封信一次! –