我为我的生活无法弄清楚为什么我的桌子没有显示结果。它充当值但不显示任何文本。我需要根据用户的选择只显示食物的类型。
数组
$aList = array ();
$aList[0] = array();
$aList[0]['Animal'] = "Bear";
$aList[0]['Habitat'] = "Forest";
$aList[0]['Food'] = "Meat";
$aList[1] = array();
$aList[1]['Animal'] = "Deer";
$aList[1]['Habitat'] = "Forest";
$aList[1]['Food'] = "Grass";
$aList[2] = array();
$aList[2]['Animal'] = "Pig";
$aList[2]['Habitat'] = "Farm";
$aList[2]['Food'] = "Mixed";
$aList[3] = array();
$aList[3]['Animal'] = "Cow";
$aList[3]['Habitat'] = "Farm";
$aList[3]['Food'] = "Grass";
$aList[4] = array();
$aList[4]['Animal'] = "Sheep";
$aList[4]['Habitat'] = "Farm";
$aList[4]['Food'] = "Grass";
$aList[5] = array();
$aList[5]['Animal'] = "Camel";
$aList[5]['Habitat'] = "Desert";
$aList[5]['Food'] = "Grass";
$aList[6]['Animal'] = "Scorpion";
$aList[6]['Habitat'] = "Desert";
$aList[6]['Food'] = "Meat";
功能
function showList($Food){
// Use the global keyword to tell the PHP engine to find the variable $classList outside of the function. Without this, the PHP engine will only look for $classList inside a function.
global $aList;
// Set up a variable $tbl to store the HTML output (class list table)
// Note that the <table></table> tags and the table header row are outside of the foreach loop so that they are not repeated in each iteration of the loop.
$tbl = "<table border=1>";
$tbl = $tbl."<tr><th>Animal</th><th>Habitat</th><th>Food</th></tr>";
foreach ($aList as $Animal){
if (isset($_POST['submit'])) {
$food = strtolower($_POST['Food']);
if (strtolower($Animal['Food']) == $food)
$tbl .= "<tr><td>{$Animal[$food.'Animal']}</td><td>{$Animal[$food.'Habitat']}</td><td>{$Animal[$food.'Food']}</td></tr>";
}
if (isset($_POST['submit'])) {
$habitat = strtolower($_POST['Habitat']);
if (strtolower($Animal['Habitat']) == $habitat)
$tbl .= "<tr><td>{$Animal[$habitat.'Animal']}</td><td>{$Animal[$habitat.'Habitat']}</td><td>{$Animal[$habitat.'Food']}</td></tr>";
}
}
$tbl .= "</table>";
echo $tbl;
}
答案 0 :(得分:0)
您试图在循环中获得$Animal[$food.'Animal']
的值,但在您的数组中它只是$Animal['Animal']
。您正在将食物变量与键连接,但您的阵列没有任何其他键,然后是Animal,Habitat和Food。因此,您需要从$Animal
数组中的键值中获取所有$ food和$ habitat变量。