2011-05-19 45 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