这是我的示例代码,我想对id进行分组并内联日期,如下图所示
$sql_e = mysqli_query($link,"SELECT * FROM tbl_attendees");
while($sql_e_res = mysqli_fetch_array($sql_e)){
echo'<tr>
<td>'.$sql_e_res['s_usn'].'</td>
<td>'.$sql_e_res['s_name'].'</td>
';
$dt = ''.$sql_e_res['at_date'].'';
$dt = strtotime(str_replace(',', '', $dt));
$d = date('j',$dt);
$currentdays = intval(date("t"));
$i = 0;
while ($i++ < $currentdays){
if($i == $d){
$ff='<td style="text-align:center">'.$d.'</td>';
}else{
$ff='<td style="text-align:center">';
}
echo $ff;
}
echo'</tr>';
}
What i want
最佳答案
正如xQbert所说,您需要按s_usn
对查询进行排序
编辑:我的代码希望在其上工作的查询是"SELECT * FROM tbl_attendees ORDER BY s_usn asc;"
我猜想这段代码有机会进一步优化,但我尝试使我的编码风格与您的编码风格非常接近,并重用您的var名称。我还尝试将代码的可读性放在首位。试试这个代码,我几乎评论了一切
该代码是一个大循环,将结果行抛出,对于每一行,您都要检查这是否是新学生。如果是新学生,那么您将使用名为$daysTDs
的字符串构建前一个学生的出勤日期,看起来像这样的"<td>1<td><td><td><td>3<td>...."
我们将通过一个名为$attendees
的数组构建此字符串,该数组保存该学生一直在其中学习的所有时间,可能看起来像这样
$attendees = [12,10]
当遇到新学生时,我们将回显上一个学生的
$daysTDs
,并在循环结束后用</tr>
关闭行。 $daysTDs
$lastId = ""; //var to check the new students
$daysTDs = ""; // a string holding the TDs of the student e.g '<td>1<td><td><td><td>3<td>....'
$attendees = []; //array to hold the days
$currentdays = intval(date("t"));
//start query result loop
while($sql_e_res = mysqli_fetch_array($sql_e)){
if($sql_e_res['s_usn']!=$lastId){//if new student
$i = 0;
//new student ? then build the $daysTDs string from $attendees attay for the previous student
while ($i++ < $currentdays){ //fot the first student it will be empty and will not get echoed
if(in_array($i, $attendees)){$daysTDs .= "<td>$i</td>";}
else{$daysTDs .= "<td></td>";}
}
if($lastId!=""){
echo $daysTDs;//if not first student append the $daysTDs
echo'</tr>'; //if not first student, then close the row </tr>
}
$attendees = []; // flush the array for the next student
$daysTDs=""; // empty the TDs string for the next student
echo'<tr>
<td>'.$sql_e_res['s_usn'].'</td>
<td>'.$sql_e_res['s_name'].'</td>';
}
$lastId=$sql_e_res['s_usn'];
$dt = ''.$sql_e_res['at_date'].'';
$dt = strtotime(str_replace(',', '', $dt));
$d = date('j',$dt);
$attendees[]=$d; //push that day to this student attendees array
}
//after the loop is ended finish the last student row
$i=0;
while ($i++ < $currentdays){
if(in_array($i, $attendees)){$daysTDs .= "<td>$i</td>";}
else{$daysTDs .= "<td></td>";}
}
echo $daysTDs;
echo'</tr>';
检查代码,并告诉我它是否获得了预期的结果
关于php - 如何使用PHP对id进行分组和内联日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40613202/