我在PHP中遇到了一个奇怪的问题。我有一个包含一些整数值的数组。当我尝试将数组中的值与目标整数进行比较时,索引不能与数组一起使用,也不能递增。这是一个例子。
问题出在if($ 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;
}
此代码采用人名,并用星号替换名称中的字母。随机索引,公开名称中的实际字母。
答案 0 :(得分: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;
}