尝试将Javascript递归转换为PHP(很容易)


Trying to convert Javascript recursion to PHP (easy)

为了一个学校项目,我不得不将一些javascript转换为PHP,但似乎缺少了一些东西,因为完全相同的代码突然提前退出。

for(var j=0; j<asciiArray.length;j++) {
    passwordFound[location] = String.fromCharCode(asciiArray[j]);
    console.log(passwordFound.join(""));
    if (password === passwordFound.join("")) {
        document.getElementById("password").innerHTML = 'Password: ' + passwordFound.join("");
        return true;
    }
    else if (location < 2) {
        var newlocation = location+1;
        if (characterDecryptFunction(newlocation,asciiArray,passwordFound,password)) return true;
    }
}

这是PHP:

function characterDecryptFunction($index, $maxIndex, $asciiArray, $passwordFound, $password)  { 
for ($j=0;$j<count($asciiArray);++$j)
{
    $passwordFound[$index] = chr($asciiArray[$j]);
    echo "<br>" . implode("", $passwordFound);
    if ($password === implode("",$passwordFound)) {
        echo "<br>Password is:" . implode($passwordFound);
        return true;
    }
    elseif ($index < $maxIndex)
    {
        $index = $index+1;
        if (characterDecryptFunction($index,$maxIndex, $asciiArray, $passwordFound, $password) == true) return true;
    }
}
return false;}

编辑:

javascript的调用方式如下:

function decryptFunction() {
var x,y,z,password,asciiArray=[],passwordFound=[];
password="abc";
asciiArray.push(0);
asciiArray.push(32);
for (x=48;x!=58;x++) {
    asciiArray.push(x);
}
for (y=97;y!=123;y++) {
    asciiArray.push(y);
}
for (z=65;z!=91;z++) {
    asciiArray.push(z);
}
characterDecryptFunction(0, asciiArray, passwordFound,password);}

和PHP:

function decryptFunction() {
$password = $_POST["password"];
$asciiArray=array();
$passwordFound=array();
for($x=48;$x!=58;$x++) 
{
    array_push($asciiArray, $x);
}
for($x=97;$x!=123;$x++) 
{
    array_push($asciiArray, $x);
}
for($x=65;$x!=91;$x++) 
{
    array_push($asciiArray, $x);
}
for ($x=0;$x<count($asciiArray);$x++) 
{
    echo $asciiArray[$x];
}
echo $password . "<br>";
characterDecryptFunction(0, 2, $asciiArray, $passwordFound, $password); }

不更新$index似乎很重要,就像在JavaScript中不更新位置一样。因此,更改PHP代码,引入$new_index:

    $new_index = $index+1;
    if (characterDecryptFunction($new_index,$maxIndex, $asciiArray, $passwordFound, $password)) return true;

当算法从递归调用返回时,即当它回溯到以前的字符时,它应该继续它停止的地方。为此,$index必须保留其以前的值。

注意:在PHP中,就像在JavaScript中一样,当您知道表达式是布尔表达式时,不需要在if语句中与true进行比较。