Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何连续地将用户输入数据推送到$\u会话数组中,然后检索它?_Php_Session - Fatal编程技术网

Php 如何连续地将用户输入数据推送到$\u会话数组中,然后检索它?

Php 如何连续地将用户输入数据推送到$\u会话数组中,然后检索它?,php,session,Php,Session,我正试图了解PHP会话的工作方式。我只是在尝试一个刽子手游戏,第一个玩家输入一个秘密单词,第二个玩家开始一次猜一个字母 让我们假设这个秘密单词是cat,玩家两次尝试,c然后a然后s。我希望最终的输出是ca. <?php session_start(); global $word; global $guess; global $hangman; if (isset($_POST['player1'], $_POST['word'])) { $_SESSION['word']

我正试图了解
PHP
会话的工作方式。我只是在尝试一个刽子手游戏,第一个玩家输入一个秘密单词,第二个玩家开始一次猜一个字母

让我们假设这个秘密单词是
cat
,玩家两次尝试,
c
然后
a
然后
s
。我希望最终的输出是
ca.

  <?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作为字符串变量。不要推入$found[],而是像$found一样连接$guess。=$guess

您应该保存请求之间已经找到的内容,因为现在您只是在
$\u会话['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'] );

您正在用以下内容覆盖您的
$\u会话['guess']

$_SESSION['guess'] = $_POST['guess'];
每一次提交

我建议您将发布的猜测存储为字母的子数组,如:

$_SESSION['guesses'][] = $_POST['guess'];
这样你就永远不会覆盖先前的猜测

这意味着您将有一个具有以下结构类型的会话数组:

$_SESSION=[
    'player1' => 'me',
    'word'    => 'cat',
    'player2' => 'myself',
    'guesses' => ['a','c']
];
从这里,您可以在
$\u会话['word']
上调用
str\u split()
,并使用
$\u会话['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>";
}
$secret\u letters=array\u unique(str\u split($\u SESSION['word']);//独特的秘密字字母
$found_letters=array_intersect($secret_letters,$_SESSION['guesses']);//独一无二的信件
如果($secret\u letters===$found\u letters){
//玩家2猜中了所有的密信,燃放了焰火
}否则{
//一些有用的代码。。。
$not_not_found=array_diff($secret_letters,$_SESSION['guesses');
$barrelated=str_replace($not_not_found,''''.$会话['word']);//例如'ca'
$space_out=内爆(“”,str_split($下划线));//例如'ca'
$error_letters=array_diff($_SESSION['guesses',$secret_letters);//已猜测字母,但不是secret word的一部分
//当计数($错误的字母)达到您指定的限制时,猜测者就输了
$available_letters=array_diff(范围('a','z'),$会话['guesses');
$select=“”.内爆(“”,$available_字母)。“”;
}
我还应该指出,有很多方法来解决这个项目。你应该看看<代码> CurtTyChar()/<代码>,它有多种模式,你应该研究和考虑。 可能会有一些正则表达式方法对您有所帮助,但我不会为您公开这些方法

如何连续地将用户输入数据推送到$\u会话数组中,然后检索它

一种简单的方法是将变量与$\u会话数组中的元素绑定。 这是一个有用的技巧,你不会在中找到。 一个简单的例子:

$foo =& $_SESSION['foo'];
该赋值将
$foo
$\u会话['foo']
绑定到相同的值, 因此,对
$foo
的每次更新也是对
$\u会话['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);

我现在明白你的问题了。由于
found[]
数组变量始终为空,因此未保存或保留上一猜测

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

并更改以下代码行:

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

global
关键字是怎么回事?这段代码在函数或类方法中吗?使用
global
是你应该不惜一切代价避免的事情。不是现在,但最终,这就是目的
,这将覆盖每次player2进行新猜测时存储在该会话中的所有先前猜测。如何修复此问题?将
$\u会话['guesses']
放入一个数组中,然后将新猜测推入其中。然后需要遍历该数组以替换字母。首先,如果未设置此变量或会话,该怎么办?那么!empty不起作用。这将返回一个错误。第二,如果变量是isset并且没有值,那么就不需要使用该变量。为什么我使用$found[$i]?你明白这段代码的意思了吗?如果没有,那么我会向你解释:如果第一个猜测的单词不在单词中怎么办?然后它将创建一个
$found=array(“\u”、“\ u”、“\ u”)
对吗?第二次运行如果猜测在单词中,$found数组将添加新的迭代数组
$found=array(“\u”、“\ u”、“\ u”、“\ u”、”c“、”a“、“\u”)
。正确的?因为我将找到的变量存储在会话中,所以它将检索猜测词。因此,我使用索引来指示数组索引将被更改的位置。我会为每一行添加注释。抱歉,如果您无法理解每一行的用途,现在可以了吗?在第一个fiddel中,您声明了找到的索引,这就是为什么不需要使用isset,但在本例中,$\u会话['found']如果您使用,则在第一次运行时尚未声明!如果没有isset,则为空。这将返回一个错误代码。您的帖子对我来说确实很有意义,尤其是那个有用的技巧
$foo=&$\u SESSION['foo']
$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 = [];
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 
}