来自另一个文件的Php下拉菜单

时间:2016-02-24 19:52:38

标签: php arrays dropdown

我正在尝试创建一个州资本猜谜游戏,其中州将随机生成,然后从下拉列表中包含用户必须猜测资本的所有资本。无论如何,他希望我们有一个单独的数组文件。该文件名为city_info.php,数组如下所示

$state_capitals = array(
    'Alabama' => 'Montgomery',

我无法使用所有大写字母填充下拉列表。

<?php
require_once "include/session.php";

if (!isset($session->valid)) {
    header("location: login.php");
    exit();
}

require_once "include/city_info.php";
/* DO NOT MODIFY THE ABOVE LINES !!!!! */

$states   = array_keys($state_capitals);
$capitals = array_values($state_capitals);
$cities   = array_merge($capitals, $other_cities);
sort($cities);

$params = (object) $_REQUEST;
print_r($params);

if (isset($params->guess)) {
    $state_capitals = $params->capitals;
    $answer         = $params->answer;
    $cities         = $params->city;

}

?>
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta http-equiv="Cache-Control" 
  content="no-cache, max-age=0, no-store, must-revalidate" />
<title>State Capital Guess Game</title>
<style type="text/css">
body {
    padding: 10px 20px;
}
#logout {
    position: absolute;
    top: 40px;
    right: 40px;
}

div {
    width: 320px;
    padding: 10px;
    border: 3px solid black;
    border-radius: 10px;
    color: black;
    text-align:center;
    background-color:#3399ff;
    display:inline-block
}

/* 
More style rules
*/
</style>
<script type="text/javascript">window.onunload = function(){}</script>
</head>

<body>
<a id="logout" href="logout.php">Log out</a>

<h2>State Capital Guess Game</h2>

<form action="program.php" method="get">
<button type="submit">Start Over</button>
</form>

<!--- computational form -->

<div>
<p>What is the Capital of PA</p>


<select name="cities">
<?php
foreach ($city as $value):
?>
<option <?php
    if ($value == $params->city)
        echo "selected";
?>
><?php
    echo $value;
?></option>
<?php
endforeach;
?>
</select>
<input type="submit" name="choose" value="Choose" />
</form>
</div>

<?php
echo $state_capitals;
?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你说出问题的方式,这听起来像是家庭作业。许多人都非常乐意帮助完成家庭作业,但有些人并不喜欢;因此,在询问有关家庭作业的问题时,请遵循以下准则:https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions。您可能已经知道这一点,但为了以防万一,我想介绍一下基础知识。

关于你的问题。我会稍微清理一下,所以不必遵循HTML / PHP。如果您替换当前代码,这应该有效:

<select name="cities">
<?php
    $options = "";
    foreach ($cities as $value){
        $options .= '<option value="' . $value . '"';
        if ($value == $params->city)
            $options .= ' selected';
        $options .= '>' . $value . '</option>';
    }
    echo $options;
?>
</select>

这样你只需在HTML / PHP之间切换一次。希望有所帮助!