gpt4 book ai didi

javascript - 尝试将 Javascript 递归转换为 PHP(简单)

转载 作者:行者123 更新时间:2023-12-02 14:51:12 25 4
gpt4 key购买 nike

我必须为学校项目将一些 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 中的 location 一样。因此更改PHP代码,引入$new_index:

    $new_index = $index+1;

if (characterDecryptFunction($new_index,$maxIndex, $asciiArray, $passwordFound, $password)) return true;

当算法从递归调用返回时,即当它回溯到先前的字符时,它应该从中断处继续。为此,$index 必须保留其先前的值。

注意:请注意,在 PHP 中,就像在 JavaScript 中一样,当您知道表达式是 bool 值时,无需与 if 语句中的 true 进行比较.

关于javascript - 尝试将 Javascript 递归转换为 PHP(简单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com