php - 如何将用户输入数据连续推送到 $_SESSION 数组中,然后检索它?

标签 php session

我正在努力了解 PHP session 的工作方式。我只是在尝试一个刽子手游戏,第一个玩家输入一个 secret 单词,然后第二个玩家开始一次猜一个字母。

假设密码是cat,玩家尝试两次,c 然后是a 然后是s。我希望最终输出为 c a _

  <?php
session_start();

global $word;
global $guess;
global $hangman;


if (isset($_POST['player1'], $_POST['word'])) {
    $_SESSION['word'] = $_POST['word'];
    $word = $_SESSION['word'];
}

if (isset($_POST['player2'], $_POST['guess'])) {
    $_SESSION['guess'] = $_POST['guess'];
    $guess = $_SESSION['guess'];
}

$counter = 0;
$word = strtolower($_SESSION['word']);
$guess = strtolower($_SESSION['guess']);
echo $word . "<br>";
$found = [];

$counter = 0;

for ($i = 0; $i < strlen($word); $i++) {
    if ($counter < strlen($word)) {
        if (strpos($word[$i], $guess) !== false) {
            $found[] = $guess;
            $counter++;
        } else {
            $found[] = " _ ";
        }
    }
}

  print_r($found);

我没有打印出 found 数组的所有内容,而是每次只打印一个字母。但是,我希望看到上面提到的完整的连接字符串。


输出如下:

enter image description here

最佳答案

How to continuously push user input data into $_SESSION array and then retrieve it?

一个简单的方法是将变量与 $_SESSION 数组中的元素绑定(bind)。 这是您在 the manual 中找不到的有用技巧. 一个简单的例子:

$foo =& $_SESSION['foo'];

该赋值会将 $foo$_SESSION['foo'] 绑定(bind)到相同的值, 所以对 $foo 的每次更新也是对 $_SESSION['foo'] 的更新。

以下是您的刽子手游戏风格的示例用法:

<?php
session_start();

$word =& $_SESSION['word'];   //bind $word with $_SESSION['word']
$found =& $_SESSION['found']; //bind $found with $_SESSION['found']

if (isset($_REQUEST['word'])) {
    $word = str_split($_REQUEST['word']);
    $found = array_fill(0, count($word), '_');
}
if (isset($_REQUEST['guess'], $word, $found)) {
    $guess = array_fill(0, count($word), $_REQUEST['guess']);
    $found = array_replace($found, array_intersect($word, $guess));
}

echo join(' ', $found);

通过绑定(bind),$word$found 的值将被保存为 session 数据的一部分, 无需在脚本中的任何位置执行 $_SESSION['word'] = $word;$_SESSION['found'] = $found;

请注意,我使用 $_REQUEST 而不是 $_POST 以便更轻松地使用浏览器进行测试。 根据需要修改。

关于php - 如何将用户输入数据连续推送到 $_SESSION 数组中,然后检索它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485257/

相关文章:

javascript - 如何从<form action>打印?

PHP+MYSQL 需要在同一个 Windows 服务器上与 ASPX+MSSQL 一起使用

php - 我如何在mysql中放置一个数组?

php - Laravel - 自定义数据透视模型中的 belongsTo 关系不起作用

php - 如何设计 php 工具/网站中的导航?

php - MySQL:更新第一个可用列为空的行

php - Facebook 状态栏

python - Django 在哪里存储 session ?

Django session 不适用于 Ubuntu 上安装的 Apache

c# - 清除应用程序启动时的所有 session