将数组序列化为$ _POST一遍又一遍

时间:2013-08-08 01:41:57

标签: php arrays serialization

我正在练习建立一个二十一点游戏,我被困在能够击中两次。这是我的代码:

if (empty($_POST)) {
  for ($i=0; $i<2; $i++) {
    $pHand[] = array_shift($deck);
    $dHand[] = array_shift($deck);
  }
  $deck2 = serialize($deck);
  $pHand2 = serialize($pHand);
  $dHand2 = serialize($dHand);
}


elseif ($_POST['hit'] == "Hit") {
  $deck = unserialize($_POST['deck']);
  $pHand = unserialize($_POST['pHand']);
  $dHand = unserialize($_POST['dHand']);
  $pHand[] = array_shift($deck);
  $deck2 = serialize($pHand);
  $pHand2 = serialize($dHand);
  $dHand2 = serialize($deck);
}


<form method="post">
<input type="hidden" name="pHand" value="<?php echo htmlspecialchars($pHand2, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="dHand" value="<?php echo htmlspecialchars($dHand2, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="deck" value="<?php echo htmlspecialchars($deck2, ENT_QUOTES, 'UTF-8'); ?>">

这一切都很好但是如果我再次按下“Hit”,我的$ pHand数组会变成完全不同的东西。如何保持第一个“命中”的相同值,以便它可以添加到第二个,第三个等“点击”?

1 个答案:

答案 0 :(得分:0)

考虑使用$ _SESSION将数据服务器端存储在提交之间。

有些事情:

<?php
session_start();

if (empty($_POST)) 
{
  for ($i=0; $i<2; $i++) 
  {
    $pHand[] = array_shift($deck);
    $dHand[] = array_shift($deck);
  }

  $_SESSION['deck']  = $deck;
  $_SESSION['pHand'] = $pHand;
  $_SESSION['dHand'] = $dHand;
}
elseif ($_POST['hit'] == "Hit") 
{
  $deck    = $_SESSION['deck'];
  $pHand   = $_SESSION['pHand'];
  $dHand   = $_SESSION['dHand'];
  $pHand[] = array_shift($deck);
  $_SESSION['deck']  = $deck;
  $_SESSION['pHand'] = $pHand;
  $_SESSION['dHand'] = $dHand;
}