我正在寻找一种更高效、更优雅、更安全的方式来对 HTML 表中显示的数据进行排序。到目前为止,这是我想出的,它看起来有些臃肿/笨拙。
我还想到了类似将排序存储在 a 中的方法$_SESSION
,这样我就不必在 URL 中“手动”将当前选择的订单带到下一页。也许一段“安全&简单”的 JavaScript+PHP(但请不要使用框架)会有意义吗?我的想法现在转了几个小时。
<?php
$ro_arr = array(
"kid" => "kid",
"kwd" => "Keyword",
"cpc" => "ApproximateCPC",
"cmp" => "Competition",
"mov" => "MonthlyValue",
"gms" => "GlobalMonthlySearches",
"lms" => "LocalMonthlySearches",
"dfc" => "KeywordDifficulty",
"com" => "com",
"net" => "net",
"org" => "org",
);
if (!empty($_GET['ro']) && strlen($_GET['ro']) == 7 && array_key_exists($col = substr($_GET['ro'], 0, 3), $ro_arr)) {
$dir = (substr($_GET['ro'], 4, 3) == 'asc' ? "ASC" : "DESC");
$res_order = $res_arr[''. $col .''] ." ". $dir;
} else {
$_GET['ro'] = "kid_asc";
$res_order = "kid ASC";
}
?>
<!-- just for testing -->
<pre><?php echo $res_order; ?></pre>
<!-- done testing -->
<table>
<tr>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='kwd_asc')?"kwd_dsc":"kwd_asc"; ?>">Keyword</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='cmp_dsc')?"cmp_asc":"cmp_dsc"; ?>">Comp.</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='cpc_dsc')?"cpc_asc":"cpc_dsc"; ?>">Ad CPC</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='mov_dsc')?"mov_asc":"mov_dsc"; ?>">Value</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='gms_dsc')?"gms_asc":"gms_dsc"; ?>">Global Searches</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='lms_dsc')?"lms_asc":"lms_dsc"; ?>">Local Searches</a></td>
<td><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='dfc_asc')?"dfc_dsc":"dfc_asc"; ?>">Difficulty</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='com_dsc')?"com_asc":"com_dsc"; ?>">com</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='net_dsc')?"net_asc":"net_dsc"; ?>">net</a></td>
<td width="22"><a href="sort.v1.php?ro=<?php echo ($_GET['ro']=='org_dsc')?"org_asc":"org_dsc"; ?>">org</a></td>
</tr>
</table>