我正在尝试创建2个下拉菜单。一个用于显示建筑物列表,然后当用户从列表中选择建筑物时,它将显示该建筑物中的房间列表。
问题是我的代码中有错误。以下是代码:
$sql="SELECT Building, Room FROM Room WHERE Building = '".$building."'";
$sqlresult = mysql_query($sql);
$sqldataArray = array();
while($sqlrow = mysql_fetch_array($sqlresult))
{
$sqldataArray[$sqlrow['Building']];
$sqldataArray[$sqlrow['Building']]['Rooms'][$sqlrow['Room']];
}
$buildingHTML = "";
$buildingHTML .= '<select name="buildings" id="buildingssDrop">'.PHP_EOL;
$buildingHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($sqldataArray as $building => $buildingData) {
$buildingHTML .= "<option value='".$building."'>" . $building . "</option>".PHP_EOL;
}
$buildingHTML .= '</select>';
$roomHTML = "";
$roomHTML .= '<select name="rooms" id="roomsDrop">'.PHP_EOL;
$roomHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($buildingData['Rooms'] as $roomId => $roomData) {
$roomHTML .= "<option value='".$roomId."'>" . $roomId . "</option>".PHP_EOL;
}
$roomHTML .= '</select>';
我得到的错误是:
未定义变量:第372行/web/stud/u0867587/Mobile_app/create_session.php中的buildingData
这是错误的代码行:
$buildingHTML .= "<option value='".$building"'>" . $building . "</option>".PHP_EOL;
有谁知道如何解决此错误。我相信这是因为它不在另一个foreach循环中,但如果我把它放进去,那么它是否会影响下拉菜单的显示?
答案 0 :(得分:1)
你有一些问题。
这些行没有做任何事情:
$sqlrow['Building']];
$sqldataArray[$sqlrow['Building']]['Rooms'][$sqlrow['Room']];
您试图在 $buildingData
之后引用foreach
,其定义已关闭。当您的下一个foreach
循环尝试使用它时,它是null
,因为您超出了前一个foreach
的范围。 这会导致您的错误消息。
您应该考虑更高级别地查看您的应用程序逻辑,并决定如何使用伪代码进行布局。
(编辑:SO不允许你把代码块放在列表中?为什么?!)
答案 1 :(得分:0)
您没有定义任何变量:
$sqldataArray[$sqlrow['Building']];
$sqldataArray[$sqlrow['Building']]['Rooms'][$sqlrow['Room']];
应该是这样的:
$sqldataArray[$sqlrow['Building']] = "Value";
$sqldataArray[$sqlrow['Building']]['Rooms'][$sqlrow['Room']] = "Definition";
答案 2 :(得分:0)
不完全确定您想要获得的最终输出 - 您的代码存在一些逻辑问题
看一下这个小改写 - 这会产生一个&lt; select&gt;用于建筑物,以及&lt; select&gt;对于你第一栋楼的所有房间。
<?php
$sqlresult = mysql_query($sql);
$buildings = array(); // easier if you don't use generic names for data
while($sqlrow = mysql_fetch_array($sqlresult))
{
// you need to initialise your building array cells
if (!isset($buildings[$sqlrow['Building']])) {
$buildings[$sqlrow['Building']] = array('Rooms' => array());
}
// you can add the room to the building 'Rooms' array
$buildings[$sqlrow['Building']]['Rooms'][] = $sqlrow['Room']]);
}
$buildingHTML = "";
$buildingHTML .= '<select name="buildings" id="buildingssDrop">'.PHP_EOL;
$buildingHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($buildings as $building => $buildingData) {
$buildingHTML .= "<option value='".$building."'>" . $building . "</option>".PHP_EOL;
}
$buildingHTML .= '</select>';
$roomHTML = "";
$roomHTML .= '<select name="rooms" id="roomsDrop">'.PHP_EOL;
$roomHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($buildings['Building Number 1']['Rooms'] as $roomId => $roomData) {
$roomHTML .= "<option value='".$roomId."'>" . $roomId . "</option>".PHP_EOL;
}
$roomHTML .= '</select>';