代码:
<?php
echo "<h1>Testing your Trivia</h1>";
$ages['1943'] = "Casablanca";
$ages['1956'] = "Around The World in 80 Days";
$ages['1970'] = "Patton";
$ages['1977'] = "Annie Hall";
$ages['1981'] = "Chariots of Fire";
$ages['1990'] = "Dances With Wolves";
$ages['2005'] = "Crash";
$ages['2006'] = "The Departed";
echo "Give the year below won academy award<br>";
echo "<Strong>Movie: </strong> <input type='text' name='' id='' readonly='readonly' /><br>";
echo "<Strong>Year it Won the Oscar: </Strong> <form method='get'><input type='text' name='year' /></form><input type='submit' /> ";
echo '<pre>';
foreach( $ages as $key => $value){
print_r("Year: $key, Title: $value <br />");
}
echo '</pre>';
if(isset($_GET['year']))
{
if(array_key_exists($_GET['year'], $ages))
{
echo "<h2>" . $ages[$_GET['year']] . "</h2>";
}
else
{
echo 'Cannot find data';
}
}
?>
基本上尝试将其设置为我可以获取电影输入以选择随机标题并将其显示在“电影”的输入字段中,然后用户必须猜测它的制作年份。如果它们太高,它会显示一个页面,如果它太低则显示错误。
我觉得我需要添加另一个If / Else,如果高或太低。任何人?
谢谢!
答案 0 :(得分:2)
你的数组键是否有字符串?在这种情况下,它们似乎是有意义的,因为它们是整数。
<?php
$ages['1977'] = "Annie Hall";
$ages['1956'] = "Around The World in 80 Days";
$ages['1990'] = "Dances With Wolves";
$ages['2006'] = "The Departed";
$ages['2005'] = "Crash";
$ages['1943'] = "Casablanca";
$ages['1981'] = "Chariots of Fire";
$ages['1970'] = "Patton";
if(isset($_GET['year']))
{
if(array_key_exists($_GET['year'], $ages))
{
echo $ages[$_GET['year']];
}
else
{
echo 'Cannot find data';
}
}
?>
<form method="GET">
<input type="text" name="year" value="1984" />
<input type="submit" />
</form>
答案 1 :(得分:1)
如果用户从下拉菜单/单选按钮列表中提交了一个值,您可以检查$ages
数组是否设置了该年份,如果没有,则显示默认消息:
$year = $_GET['year'];
echo isset($ages[$year]) ? $ages[$year] : 'DOES NOT COMPUTE';
MVC男人可能会因为这样说(如果他们还没有)而对我有所打击,但我喜欢保持这种自足的东西。这意味着一个页面(例如,index.php
)看起来像这样:
<?php
// All of your PHP goes here.
?>
<!DOCTYPE html>
<!-- All of your HTML goes here. -->
我将从HTML开始。你会想要一个表格,如下:
<form action="" method="get">
<div>
<label>Movie Year: <input type="text" name="year" />
<input type="submit" value="Look Up Movie" />
</div>
</form>
请注意,表单的action
留空。这意味着表单将提交到当前页面。这就是文档顶部的PHP发挥作用的地方。
您首先要初始化您的年份和标题数组:
$ages = array(
'1977' => 'Annie Hall',
// ...
'1970' => 'Patton'
);
然后检查用户是否提交了表单:
if (isset($_GET['year'])) {
$year = $_GET['year'];
$message = isset($ages[$year]) ? 'The film for that year is called '.$ages[$year].'.' : 'There is no film for that year.';
}
这会将变量$message
设置为您要向用户显示的某些文本。
现在我们最后一次跳回到文档的HTML部分,就在表单上方:
<?php
if (!empty($message)) {
echo '<p>', $message, '</p><p>Want to go again?</p>';
}
?>
你有它,一个可搜索的电影片组,按年组织。