如何在查询中迭代数组的值?

时间:2017-08-09 13:39:30

标签: php

我想从下面的查询中迭代数组$code$per_section的值。我应该使用什么循环方法?或者这是正确的做法?

   //total students
    $count_query=mysql_query("select total_students from subject where teacherid = '$get_id'");
    while($count_row=mysql_fetch_array($count_query)){ 
    $total += $count_row['total_students'];
    }

    $query = mysql_query( "Select code,total_students from subject where teacherid='$get_id'");
        while($result=mysql_fetch_assoc($query))){
         $section = ($result['total_students']/ $total)*30;
         $per_section[] = round($section, 0, PHP_ROUND_HALF_UP);
         $code[] = $result['code'];
        }

    //perform this statement for a number of times depending on the number of array of $code..
        $user_query=mysql_query("select * from result where subject_id ='$code' and faculty_id = '$get_id'LIMIT $per_section ")or die(mysql_error());                   
        while($row=mysql_fetch_assoc($user_query)){
            ...
         }

示例数据: 主题表

code    total_students   teacherid

IT230         45         11-0009
IT213         44         11-0009
IT214         40         11-0009

结果表

subject__id    faculty_id

IT230          11-0009
IT213          11-0009
IT214          11-0009

预期结果: 我想只显示与结果表匹配的30条学生记录。

由于该老师的学生总数为45,44,40 = 129.这是$per_section

IT230只需要学生=(45/129)* 30 = 10.46或者我只需要11个结果。

IT213只需要学生=(44/129)* 30 = 10.23或者我只需要10个结果。

IT214只需要学生=(40/129)* 30 = 9.3或者我只需要9个结果。

我想在IT230中搜索记录,只选择其中的11个。 IT213仅为10,IT214为9.由于我只有3条记录,因此只会显示这三条记录。

2 个答案:

答案 0 :(得分:0)

使用一个连接两个表的查询:

SELECT s.total_students, s.code, r.*
FROM students AS s
LEFT JOIN result AS r ON r.subject_id = s.code
WHERE s.teacher_id = '$get_id' AND r.faculty_id = '$get_id'
ORDER BY s.code

然后您可以在一个循环中获取所有信息:

while ($result = mysqli_fetch_assoc($query)) {
    if (!isset($per_section[$result['code']]) {
        $per_section[$result['code']] = round($result['total_student']/$total*30, 0, PHP_ROUND_HALF_UP);
        $code[] = $result['code'];
    }
    if ($result['subject_id'] !== null) {
        // do stuff with columns from result table here
    }
}

答案 1 :(得分:0)

正如您对问题的评论中所提到的,通过<div class="col-lg-2 col-md-2 col-sm-12 col-xs-12"> <select class="selectpicker show-tick"> <option>1</option> <option>2</option> </select> </div> PDO两个表格使用准备好的陈述是更好的做法:

JOIN
相关问题