按HTML表格列对查询结果进行排序

时间:2013-06-17 02:46:39

标签: php javascript html sorting

我正在寻找一种更强大的高效优雅安全方式来对HTML表格中显示的数据进行排序。这是我到目前为止所提出的,它看起来有点臃肿/无趣。

我还想到了将排序存储在$_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>

2 个答案:

答案 0 :(得分:1)

如果您使用两个参数而不是一个参数,则可以将代码量减少到近一半:

  1. 您要排序的参数:kid,com,net,org ......
  2. 订单:asc,dsc

答案 1 :(得分:0)

如果您的牌桌不是太大且您对使用jQuery没有反感,请使用tablsorter。一旦你进入成千上万行,客户端排序就会变得有点不知所措。