2017-03-03 133 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

是的,但这没关系。我只需要揭穿这封信一次! –