开发者

Make random groups of students from database based on grades

I have table with 30 students with grades from 1 to 5. How to make 6 different students group which contains five randomly selected students? Each group must have five students and each of those five students must have different grade.

First group: st开发者_如何学编程udent1 (grade1), student2 (grade2), student3 (grade3), student4 (grade4), student5 (grade5)


Pull in the data from the table, structure the results to group by grade, so you have array('Grade1' => array('Student1','Student2','etc.'), 'Grade2' => array('Student3','Student4','etc)) and so forth. Randomize the sub arrays like:

foreach($students as $key=>$student)
{
    shuffle($students[$key]);
}

Then you can just go across the arrays so $group[0] would be = to array($students['Grade1'][0],$students['Grade2'][0],$students['Grade3'][0],etc.) which could be done with a for() loop.

You could do most of the work with randomizing and limit your results in the SQL query by doing something like:

"SELECT * FROM `Students` WHERE `Grade` = 'Grade1' ORDER BY RAND() LIMIT 6"

to get 6 randomly ordered results from the table for that grade to begin with. Of course, that would require a separate SQL query for each of the grades. There's probably a way to get 6 random results for each grade in a single query.

I'm also assuming that the same student cannot be in two different groups and there are the same students in each group. If they're uneven, and they can be in more than one group, then you'd have to randomly select one of the students from the grade to fill the spot, which could easily done with something like $students['GradeX'][mt_rand(0,count($students['GradeX']) - 1)]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜