我试图在php中创建一个下拉菜单但是我似乎无法在菜单中出现多个选项我觉得它可能与类列表数组的大小有关,我该如何解决这个问题?有没有更好的方法来解决这个问题?以下是我的代码:
<?php
class Classlist {
private $classCount = 0;
public function show() {
$count = null;
$classCount = $this-> _countClass($count);
for($i = 0; $i < $classCount + 1; $i++){
$content = $this-> _classList();
}
return $content;
}
private function _countClass(){
$user_id = $_SESSION['user_id'];
$link = mysqli_connect('*******','******','*******#','------');
$result = mysqli_query($link, "SELECT * FROM student_class WHERE user_id = '$user_id';") or die(mysql_error($link));
$classList = array();
while($row = mysqli_fetch_assoc($result)){
$classList[$row['class_id']][] = $row;
}
return sizeof($classList);
}
private function _classList(){
$link = mysqli_connect('*******','******','*******#','------');
$userID = $_SESSION['user_id'];
$result = mysqli_query ($link, "SELECT * FROM student_class WHERE user_id = '$userID';") or die(mysql_error());
$classes = array();
while($row = mysqli_fetch_assoc($result)){
$classes[$row['class_id']][] = $row;
}
foreach($classes as $c_id => $value){
$className = array();
$class_id = json_encode($c_id);
$query_classname = mysqli_query($link, "SELECT class_name FROM classes WHERE class_id ='$c_id';") or die(mysql_error());
while($row = mysqli_fetch_assoc($query_classname)){
$className[$row['class_name']][] = $row;
}
}
$content = '';
foreach($className as $name => $value){
$content .='<option value ="'. $name.'">'. $name.'</option>';
}
return $content;
}
}
?>
答案 0 :(得分:0)
似乎你在foreach的每次迭代($ class为$ c_id =&gt; $ value)循环中清空$ className数组,所以你最终在数组中有一个项目(实际上是最后一项)。将$ className = array()放在循环之外。
$className = array();
foreach($classes as $c_id => $value){
$class_id = json_encode($c_id);
$query_classname = mysqli_query($link, "SELECT class_name FROM classes WHERE class_id ='$c_id';") or die(mysql_error());
while($row = mysqli_fetch_assoc($query_classname)){
$className[$row['class_name']][] = $row;
}
}