要在PHP中为表格添加排序功能,可以使用以下方法:
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'age' => 35]
];
usort()
函数,并传入一个自定义的比较函数。比较函数将根据所需的列对数组进行排序:function sort_table($array, $column, $order = 'asc') {
usort($array, function ($a, $b) use ($column, $order) {
$comparison = strcmp($a[$column], $b[$column]);
if ($order == 'desc') {
return -$comparison;
} else {
return $comparison;
}
});
return $array;
}
<thead>
<tr>
<th><a href="?sort=id">ID</a></th>
<th><a href="?sort=name">Name</a></th>
<th><a href="?sort=age">Age</a></th>
</tr>
</thead>
<tbody>
<?php foreach ($sorted_users as $user): ?>
<tr>
<td><?php echo $user['id']; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['age']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
if (isset($_GET['sort'])) {
$sort_column = $_GET['sort'];
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'asc';
$sorted_users = sort_table($users, $sort_column, $sort_order);
} else {
$sorted_users = $users;
}
现在,当用户点击表头的排序链接时,表格将根据所选列进行排序。你可以通过更改$order
参数来实现升序(asc)和降序(desc)排序。