嘿,我是PHP的新手,我正在尝试从用户那里获取放入游戏表单中的值。每次用户输入文本并单击提交时,都应将其添加到数组中。每当它在页面底部显示当前在有序列表中的所有猜测,直到用户得到正确的答案并获胜。
<?php
$count =0;
$guesses = array();
if(isset($_POST['submit']))
{
$count = $_POST['count'];
for($r =0; $r < $count; $r++)
{
$guesses[$r] = $_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "hidden" name = "count" value = "<?php $count +=1;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < $count; $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
我一直得到一个未定义的偏移:0。我做了一些阅读,我知道它与我填充数组错误或调用索引错误有关。希望您能帮我告诉我如何解决这个问题。谢谢。
输出类似于:
你的猜测: 蓝色 红色 等
答案 0 :(得分:0)
编辑:
问题是你最重要的是没有回应你表单中的$ count,你只需增加它。所以post变量是空的。另外,在添加到数组后而不是在帖子中增加它。
<?php
if( !isset( $count ) ){
$count =0;
}
$guesses = array();
if(isset($_POST['submit'])) {
$guesses[$count] = $_POST['word'];
$count++;
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < count( $guesses); $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
答案 1 :(得分:0)
试试这段代码:
<?php
$guesses = array();
if(isset($_POST['submit']))
{
if($_POST['guesses'] != '')
$guesses = explode('|', $_POST['guesses']);
if(trim($_POST['word']))
$guesses[] = trim($_POST['word']);
}
?>
<h3>Guess the word I'm thinking</h3>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name= "word" value="" />
<input type="hidden" name="guesses" value="<?php echo count($guesses)? implode('|',$guesses):''; ?>" />
<input type="submit" name="submit" value="Make a Guess" />
</form>
<ol>
<?php foreach($guesses as $guess) { ?>
<li><?php echo $guess;?></li>
<?php } ?>
</ol>
答案 2 :(得分:0)
看看您是否不想使用Session变量,那么您必须设置用户在隐藏输入标记中输入的值。以下是获取特定结果所需的代码:
<?php
$guesses="";
if(isset($_POST['submit']))
{
$guesses= $_POST['count']." ".$_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "Word"/>
<input type = "hidden" name = "count" value = "<?php echo $guesses;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
$count = explode(" ", $guesses);
foreach($count as $val)
{
if($val!= ''){
?>
<li><?php echo $val;?></li>
<?php
}
}
?>
</ol>