我正在运行以下代码,该代码运行查询,获取班级中所有的student_id,然后为每个学生id获取所有成绩。我的问题是,放回数组中的数据并返回第二个,第三个等学生运行for循环时不会保留在数组中。有没有办法将数据保留在数组中并继续添加?我在下面提供了一些代码来帮助描绘图片。谢谢大家
$sql = "SELECT student_id FROM users_table WHERE class_id ='5'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$row_cnt = mysqli_num_rows($result);
$students = array();
for($y=0; $y<$row_cnt; $y++)
{
array_push($students, $row['student_id']);
$sql2 = "SELECT student_grade FROM grades_table WHERE student_id ='".$students[$y]."'";
$result2 = $db->sql_query($sql2);
$row2 = $db->sql_fetchrow($result2);
$row_cnt2 = mysqli_num_rows($result2);
for($z=0; $z<$row_cnt2; $z++)
{
array_push($students, array($row['student_grade']));
}
}
最佳答案
在第二个sql2部分中,您可能想要执行以下操作:
for($z=0;$z<$row_cnt2;$z++) {
$students[$row['student_id']] = $row['student_grade'];
}
这样做,您的数组不会被覆盖,并且您将得到如下内容:
array(
5 => "A"
6 => "B"
)
其中5是student_id,A是年级。
但是,当然,也可以使用提供的JOIN查询轻松解决此问题。
您正在编写的“较大查询”是什么?
关于php - 如何继续添加到该阵列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25066988/