2011-05-19 47 views
0

请你检查一下这段代码,看看它为什么返回一个未定义的偏移量:以及它如何修复。为什么我的php下拉表单导致未定义的偏移量

options.php

<?php 
$options = array(); 
$options["PC 1"] = array("year"=>"2000","colour"=>"blue"); 
$options["PC 2"] = array("year"=>"2003","colour"=>"pink"); 
$options["PC 3"] = array("year"=>"2006","colour"=>"orange"); 
?> 

的index.php

<html> 
<body> 
<form name="input" action="test.php" method="post"> 
Device Name: <?php 
include("options.php"); 
echo '<select name="option">'; 
foreach($options as $name => $values) 
{ echo '<option value="' .$name .'">' .$name .'</option>'; 
} 
echo '</select>'; 
?> 
<input type="submit" value="Submit" /> 
</form> 
</body> 
</html> 

test.php的

<?php 
include("options.php"); 
$chosenValue = $_POST['option']; 
list($year,$colour) = $options[$chosenValue]; ---- here is the error line 

echo $year; 
echo $colour; 

?> 

感谢

+0

什么是确切的错误?如第8行'注意:未定义偏移'偏移' – fin1te 2011-05-19 12:09:51

+0

注意:未定义偏移量:1在C:\ wamp \ www \ wol \ test.php中对第4行 – Michael 2011-05-19 12:11:45

+0

它对于偏移量0和1 – Michael 2011-05-19 12:18:00

回答

0

我想这是因为关键的数组中$options在其中有空格。这在PHP中完全有效/合法,但在HTML中,当表单提交时它不喜欢它。

尝试将它们更改为$options["PC1"]等,看看它是否修复它。

编辑:从PHP manual - list() only works on numerical arrays and assumes the numerical indices start at 0.

尝试改变test.php到:

<?php 
include("options.php"); 
$chosenValue = $_POST['option']; 
$year = $options[$chosenValue]['year']; 
$colour = $options[$chosenValue]['colour']; 

echo $year; 
echo $colour; 
?> 
+0

不是。尝试单词,仍然有错误 – Michael 2011-05-19 12:15:06

+0

编辑我的文章,并附上新的答案 – fin1te 2011-05-19 12:19:14

+0

Yay!谢谢,友好!:) – Michael 2011-05-19 12:21:17

0

更改您访问年和颜色test.php的方式,list()似乎并不一道很好地工作非数字指数。一个在PHP文档的用户发表的评论适合您的需求

http://www.php.net/manual/en/function.list.php#53420

或者只是去

$data = &$options[$chosenValue]; 
echo $data['year']; // etc