我有一个包含列的表,这些列在单击标题时按降序排序,但是我想在再次单击时反转排序。
每次点击标记时如何更新变量$ sort,还是有更好的方法尝试执行此操作?
$orderBy = array('one','two','three');
$sort = "DESC";
$order = 'column1';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
$query = "SELECT column1, column2, column3 ORDER BY $order $sort LIMIT 20";
HTML
<tr>
<th>
<a href="?orderBy=column1">1</a>
</th>
<th>
<a href="?orderBy=column2">2</a>
</th>
<th>
<a href="?orderBy=column3">3</a>
</th>
</tr>
答案 0 :(得分:2)
两种方式:
PHP方式 - 没关系,但每次请求都会重新加载数据。
<?php
// the very top of the page: start a session to remember the previous options
session_start();
if (!isset($_SESSION["order"]))
$_SESSION["order"] = array("col" => false, "dir" => false);
// set defaults
$dir = 0;
$col = "column1";
$orderBy = array("column1", "column2", "column3");
$orderDir = array("DESC", "ASC");
// check $_GET data
if (isset($_GET["orderBy"]) && in_array($_GET["orderBy"], $orderBy)) {
$col = $_GET["orderBy"];
}
// check if same col is clicked as last time
// if it is the same => change the order, if not => use default
if ($_SESSION["order"]["col"] == $col) {
// 1 becomes 0, 0 becomes 1
$dir = 1 - $_SESSION["order"]["dir"];
}
// remember current options
$_SESSION["order"]["col"] = $col;
$_SESSION["order"]["dir"] = $dir;
// set the order
$sort = $orderDir[$dir];
// set the correct query
$query = "SELECT column1, column2, column3 ORDER BY $col $sort LIMIT 20";
Javascript方式:
答案 1 :(得分:0)
in_array()检查数组中是否存在值
使用它:
$orderBy = array('column1','column2','column3');