我有一段代码可以读取SQL数据并将其转换为JSON格式
$sql = "SELECT students.studentnumber, students.firstname, students.lastname, badge_id FROM students
INNER JOIN student_has_badge
WHERE student_has_badge.badge_id = 10
AND student.studentnumber = student_has_badge.studentnumber
ORDER BY lastname ASC
LIMIT 50;";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//creating an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
mysqli_close($connection);
我从中获得的输出如下所示:
[{"studentnumber":"11111","firstname":"John","lastname":"Smith","badge_id":"10"},
{"studentnumber":"1","firstname":"Nick","lastname":"Smith","badge_id":"10"},
{"studentnumber":"500740442","firstname":"Jason","lastname":"Baker","badge_id":"10"},
{"studentnumber":"00000","firstname":"Tim","lastname":"Smith","badge_id":"10"}]
现在我想把这些数据放在一个HTML表格中,我尝试了各种各样的方法,但是没有它们有效,有人能指出我正确的方向吗?
答案 0 :(得分:0)
<?php
$emparray ='[{"studentnumber":"11111","firstname":"John","lastname":"Smith","badge_id":"10"},{"studentnumber":"1","firstname":"Nick","lastname":"Smith","badge_id":"10"},{"studentnumber":"500740442","firstname":"Jason","lastname":"Baker","badge_id":"10"},"studentnumber":"00000","firstname":"Tim","lastname":"Smith","badge_id":"10"}]';
$emparray = json_decode($emparray,1);
echo '<table border="1"><tr><th>Student#<th>First name</th><th>lastname</th><th>badge id</th></tr>';
foreach($emparray as $key => $value){
echo '<tr><td>'.$value['studentnumber'] . '</td><td>'.$value['firstname'] . '</td><td>'.$value['lastname'] . '</td><td>'.$value['badge_id'] .'</td></tr>';
}
echo '</table>';
?>
答案 1 :(得分:0)
如果你想要一个PHP解决方案,那么你不需要JSON数据,只需从原始数组创建一个表。
<?php
echo '<table id="emparray"><tr>'
.'<th class="studentnumber">Student Number</th>'
.'<th class="firstname">First name</th>'
.'<th class="lastname">Last name</th>'
.'<th class="badge_id">Badge ID</th>'
.'</tr>';
foreach ($emparray as $e) {
echo '<tr><td class="studentnumber">'.$e['studentnumber'].'</td>'
.'<td class="firstname">'.$e['firstname'].'</td>'
.'<td class="lastname">'.$e['lastname'].'</td>'
.'<td class="badge_id">'.$e['badge_id'].'</td></tr>';
}
echo '</table>';
?>