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

时间:2018-01-28 10:19:22

标签: php session

我正试着绕过PHP会话的工作方式。我只是尝试一个刽子手游戏,第一个玩家输入一个秘密词,然后第二个玩家开始猜测一个字母。

让我们说秘密字是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

6 个答案:

答案 0 :(得分:3)

  

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

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

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

该分配会将$foo$_SESSION['foo']绑定到相同的值, 因此$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);

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

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

答案 1 :(得分:0)

将$ found作为字符串变量。而不是推入$ found [],连接$ guess就像$ found。= $ guess;

答案 2 :(得分:0)

您应该保存已在请求之间找到的内容,因为现在您只是在$_SESSION['word']搜索上一个请求中的字符。

if ( isset($_POST['player1']) && !empty($_POST['word']) ) {
    $_SESSION['word'] = str_split( $_POST['word'] );
    // ceate empty array for storing the already found chars
    $_SESSION['found'] = str_split( str_repeat( " ", strlen($_POST['word']) ) );        
}

if ( isset($_POST['player2']) && !empty($_POST['guess']) ) {

    array_walk( $_SESSION['word'], function( $v, $k ) {
        if ( $v == $_POST['guess'] )
            $_SESSION['found'][$k] = $v;
    });
}


if ( $_SESSION['word'] == $_SESSION['found'] ) 
    echo 'Game Over';

print_r( $_SESSION['found'] );

答案 3 :(得分:0)

您正在使用以下代码覆盖$_SESSION['guess']

$_SESSION['guess'] = $_POST['guess'];

每次提交。

我建议您将已发布的猜测存储为以下字母的子阵列:

$_SESSION['guesses'][] = $_POST['guess'];

然后你永远不会覆盖早期的猜测。

这意味着您将拥有一个具有此类结构的会话数组:

$_SESSION=[
    'player1' => 'me',
    'word'    => 'cat',
    'player2' => 'myself',
    'guesses' => ['a','c']
];

在此处,您可以在str_split()上致电$_SESSION['word'],并使用$_SESSION['guesses']和数组比较功能检查已发现/剩余的字母。

以下是一些未经测试的代码部分,可以帮助您...

session_start();

if (!isset($_SESSION['player1'], $_SESSION['word'])) {  // no stored player1 or word
    if (!isset($_POST['player1'], $_POST['word'])) {  // no posted player1 or word
        // show form with player1 and word fields
    } else {
        $_SESSION=['player1'=>$_POST['player1'],'word'=>strtolower($_POST['word'])]; // store player1 and word
    }
} elseif (!isset($_SESSION['player2'], $_SESSION['guesses'])){  // no stored player2 or guesses
    if (!isset($_POST['player2'], $_POST['guess'])) {  // no posted player2 or guess
        // show form with player2 and first guess
    } else {
        $_SESSION['player2'] = $_POST['player1'];  // store player2
        $_SESSION['guesses'] = [strtolower($_POST['guess'])];  // store guessed character as first element of subarray
    }
} elseif (isset($_POST['guess'])) {
    $_SESSION['guesses'][] = strtolower($_POST['guess']);  // store guessed character
}

进一步向下的脚本是一些......

$secret_letters=array_unique(str_split($_SESSION['word']));  // unique secret word letters
$found_letters=array_intersect($secret_letters,$_SESSION['guesses']);  // unique found letters
if($secret_letters===$found_letters){
    // player2 guessed all of the secret letters, set off fireworks
}else{
    // some useful bits of code...

    $not_yet_found=array_diff($secret_letters,$_SESSION['guesses']);
    $underscored=str_replace($not_yet_found,'_',$_SESSION['word']);  // e.g. 'ca_'
    $space_out=implode(' ',str_split($underscored));  // e.g. 'c a _'

    $wrong_letters=array_diff($_SESSION['guesses'],$secret_letters);  // letters guessed but not part of secret word
    // when count($wrong_letters) reaches your designated limit, then the guesser loses

    $avaliable_letters=array_diff(range('a','z'),$_SESSION['guesses']);
    $select="<select name=\"guess\"><option>".implode('</option><option>',$available_letters)."</option></select>";
}

我还应该注意,有很多方法可以解决这个项目。你应该看看count_chars(),它有多种模式你应该研究和考虑。

会有正则表达式方法可能会有所帮助,但我不会为您开放。

答案 4 :(得分:0)

如果我理解正确,问题在于你的病情。请看下面的解决方案

for ($i = 0; $i < strlen($word); $i++) {
    if ($word[$i] === $guess[$i]) {
       $found[] = $guess[$i];
    } else {
      $found[] = " _ ";
    }
}
print_r($found)

不需要

global $word;
global $guess;
global $hangman
$counter`

答案 5 :(得分:0)

我现在看到了你的问题。你没有保存或保持之前的猜测,因为你的found[]数组变量总是空的。

尝试将找到的结果保存在会话中

并更改以下代码行:

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

TO:

$counterWord = strlen($word);
for ($i = 0; $i < $counterWord ; $i++) {
    if (strpos($word[$i], $guess) !== false) {
        $found[$i] = $guess; // $i indicates what index should be changed

    } else {

        if(!isset($found[$i])){
         $found[$i] = "_";

       }


}


$_SESSION['found'] = $found;

并在$found数组变量的声明下添加此行代码:

$found = [];
if(isset($_SESSION['found'])){ //checker if the variable is set and not empty
     $found = $_SESSION['found']; // getting the value of found and store it in found variable 
}