2012-05-24 3 views
3

나는 생물에 관한 게임을 만들기 위해 PHP 스크립트를 작성하기 시작했다. 예/아니오 질문이 4 개 있으며, 무엇을 하려는지 2 개의 버튼을 표시하는 함수를 작성한다. yes와 no를 입력하고 예를 들어 yes1과 no1과 같은 함수를 실행할 때마다 다른 이름을주고 다음에 함수가 실행될 때 버튼의 이름은 yes2와 no2가됩니다.매번 변수를 1 씩 증가시키는 PHP 함수

나는이 작업을 이미 시도했지만 제대로 작동하지 않습니다. 아래 코드는 제가 지금까지 해본 코드입니다.

<?php 
session_set_cookie_params(2592000); 
session_start(); 
?> 

<html> 
<head> 
<title>Creature Guessing Game</title> 
</head> 
<body> 
<h1>Creature Guessing Game</h1> 
<p> Welcome to the creature guessing game! </p> 
<p>Click the button below to start or restart the game </p> 

<form method="post" action="Creatures.php"> 
<input type="submit" name="start" value="Start Game" /> 
</form> 
<?php 
$questions = array('Does the creature live on land?', 'Does it have wings?', 'Does it live near water?', 'Can it fly?'); 
function repeat() 
{ 
$number = 0; 
$number++; 
echo "<form method ='post' action='Creatures.php'> 
<input type='submit' name='yes'.$number value='Yes' /> 
<input type='submit' name='no'.$number value='No' /> 
</form>"; 

} 
//If form not submitted, display form. 
if (!isset($_POST['start'])){ 
?> 
<?php 
} //If form is submitted, process input 
else{ 
switch($_POST) 
{ 
case yes1: 
echo $questions[0]; 
repeat(); 
break; 
case no1: 
echo $questions[1]; 
repeat(); 
break; 
case yes2: 
echo $questions[2]; 
repeat(); 
break; 
case no2: 
$questions[3]; 
repeat(); 
} 
} 
?> 
</body> 
</html> 
+0

전화 할 때마다'반복()''$ number'를'0'으로 설정 한 다음 그것을 증가시킵니다. '$ questions'를 설정 한 후'repeat()'가 정의되기 전에'$ number'를 설정하면 어떨까요? – robert

+0

방금 ​​시도했지만 어떤 이유로 $ number가 0으로 설정되었는데, 아무리 여러 번 호출해도 숫자 $ 0이 남아 있습니다. – Harry12345

답변

4

이렇게하려면 요청간에 상태를 유지해야합니다.

function repeat() { 
     $number = $_SESSION['number']; 
     $number++; 
     echo "<form method ='post' action='Creatures.php'> 
    <input type='submit' name='answer' value='Yes' /> 
    <input type='submit' name='answer' value='No' /> 
    </form>"; 
    $_SESSION['number'] = $number; 
} 

스위치

if($_POST['answer']=='Yes') { 
     switch($_SESSION['number']) { 
      case 1: 
      break; 
      case 2: 
      break; 
     } 
    } else { 
     switch($_SESSION['number']) { 
      case 1: 
      break; 
      case 2: 
      break; 
     } 
    } 
+0

고마워요! 이 함수는 현재 원했던 것처럼 작동하지만 switch 문은 여전히 ​​작동하지 않지만 스위치 대신 무언가를 시도 할 수 있습니다. – Harry12345

+0

답변을 스위치를 – ShaaD

+0

수리이 여전히 작동하지 않습니다, 스위치 문을 어떤 단추 (예 또는 아니요) 누를에 따라 다른 일을 원하는 어쩌면 거기에 스위치 조건을 yes1 만들 수있는 방법이 있습니다. 첫 번째 경우는 true (즉, $ _POST = 'yes1')이고 두 번째 경우는 참이 아닌 경우입니다. 당신이 이해한다면 몰라? 가능하다면 가능합니까? – Harry12345

0

페이지를 제출할 때마다 값을 잃어 버리기 때문에 세션에 '번호'를 저장해야합니다.

2

I 아니에요 허용 대답과 일치 : 다음 세션없이 그것에 대해 이동하는 쉬운 방법입니다

function repeat() { 
     static $number = 0; 
     $number++; 
     echo "<form method ='post' action='Creatures.php'> 
    <input type='submit' name='answer' value='Yes' /> 
    <input type='submit' name='answer' value='No' /> 
    </form>"; 
}