大家好我试图将我的数据表分组以显示部门列出的用户,例如:
IT DEPARTMENT
Name Phone Email Extension
Bob 99393 ksand@sda 8484
但我的显示如下:
Name Phone Email Extension Department
Bob 99393 ksand@sda 8484 IT
我做了一些关于数据表分组的阅读,但是他找到了解释它如何工作以及如何实现它的任何东西。
我的代码如下。如果有人能指出我的帮助,我将不胜感激,谢谢。
<?php
require_once"connection.php";
$contacts = array();
$all_contacts = "select * from contacts where contact_status = '1'";
$sql_all_contacts = $conn->query($all_contacts);
$total_contacts = $sql_all_contacts->num_rows;
while ($row = mysqli_fetch_assoc($sql_all_contacts)) {
$contacts[] = $row;
}
?>
<html>
<head>
<?php include"includes/head.inc"; ?>
</head>
<body>
<div class="wrapper">
<!-- header section -->
<?php include"includes/header.inc"; ?>
<!-- content section -->
<div class="content">
<div class="floatl"><h1><?php echo $total_contacts ?> Contact(s) Total</h1></div>
<a class="floatr" href="insert_contact.php"><input class="cancel_contact_button" type="button" value="New Contact"></a> $
<div class="clear"></div>
<hr class="pageTitle">
<table border ="1" style="width:100%" id="contactsTable" class="display">
<thead>
<tr align="left">
<th>Name:</th>
<th>Email:</th>
<th>Department:</th>
<th>Extension:</th>
<th>Cellphone:</th>
<th>Actions</th>
</tr>
</thead>
<tr align="left">
<th>Name:</th>
<th>Email:</th>
<th>Department:</th>
<th>Extension:</th>
<th>Cellphone:</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($contacts as $contact) {?>
<tr>
<td><?php echo $contact["name"];?></td>
<td><?php echo $contact["email"]; ?></td>
<td><?php echo $contact["department"]; ?></td>
<td><?php echo $contact["extension"]; ?></td>
<td><?php echo $contact["cellphone"]; ?></td>
<td><a href="update_contact.php?id=<?php echo $contact["contact_id"]; ?>"><i class="fa fa-p$
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
由于您已经在进行while
循环以将数据库行添加到数组中,因此可以使用Department作为键。这会按部门对联系人进行分组,您可以运行嵌套的foreach
循环。
while ($row = mysqli_fetch_assoc($sql_all_contacts)) {
$contacts[$row['Department']][] = $row;
}
foreach
循环:
foreach ($contacts as $department => $contactGroup) {
echo $department;
foreach($contactGroup as $contact) {
// output your contact here
}
}