<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
<meta charset="UTF-8" />
</head>
<body>
<form method="get">
<div>Name
<input name="name" size="15" type="text" />
</div>
<select multiple="yes" name="colors[]">
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
<option> 5 </option>
</select>
</form>
<?php
$number=10;
echo "hello";
if (isset($_GET["name"])){
echo " ".$_GET["name"];
echo "<br />";
}
echo count($_GET["colors"]), " ", $_GET["colors"], "<br />";
echo $_GET[$colors[0]]," is your first color.";
if(isset($_GET["$colors"])){
echo "You must like ";
for($colornum=0;$colornum<count($_GET["$colors"]);$colornum++){
echo $_GET[$colors[$colornum]]," ";
}
}
?>
</body>
</html>
为什么这不起作用?选择倍数不会在数组中输出,也不可能 有很多调试的东西对我的理解不大。我得到未定义的索引和变量错误。选择选项1-3后,这是我的输出:
Name
hello jimbo1qaz
3 Array
Notice: Undefined variable: colors in E:\xampp\htdocs\myform.php on line 28
Notice: Undefined index: in E:\xampp\htdocs\myform.php on line 28 is your first color.
Notice: Undefined variable: colors in E:\xampp\htdocs\myform.php on line 29
答案 0 :(得分:3)
//this should be $_GET['colors'][0]
echo $_GET[$colors[0]]," is your first color.";
//the , is wrong, you need to use . (point)
echo $_GET[$colors[0]]," is your first color.";
//Delete the $
if(isset($_GET["$colors"])){
//it's $_GET['colors']
for($colornum=0; $colornum<count($_GET["$colors"]); $colornum++){
//Here you need to use $_GET['colors'][$colornum]
echo $_GET[$colors[$colornum]]," ";
}
要输出数组,请使用print_r()而不是echo:
print_r($_GET["colors"]);
答案 1 :(得分:2)
试试这个,
<form method="POST">
<select multiple="yes" name="colors[]">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
</form>
<?php
$selected_colors = $_POST['colors'];
foreach($selected_colors AS $key=>$values)
{
echo $values.",";
}
?>
答案 2 :(得分:1)
$ _GET此时显示为数组,您没有正确引用该键,它是一个字符串而不是一个变量,见下文
<?php
$number=10;
echo "hello";
if (isset($_GET["name"])){
echo " ".$_GET["name"];
echo "<br />";
}
echo count($_GET["colors"]), " ", $_GET["colors"], "<br />";
echo $_GET["colors"][0]," is your first color.";
if(isset($_GET["colors"])){
echo "You must like ";
for($colornum=0;$colornum<count($_GET["colors"]);$colornum++){
echo $_GET["colors"][$colornum]," ";
}
}
?>
答案 3 :(得分:1)
为什么使用$colors
变量,如$_GET[$colors[0]]
。这是字符串而不是变量。而不是这样使用:
$_GET['colors'][0]