如何对更改位置字段的行重新排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何对更改位置字段的行重新排序相关的知识,希望对你有一定的参考价值。

This php function lets you reorder records on a table when you have a field used for save the position. If you have a field with position when you are editing records you probably want, for example, to move a record from position 5 to position 2, but if you already have a record in position 2 problems could raise, so how can you reorder all the records without losing informations and preserving the right order of the other elements? See how to use in the above link.
  1. function reorder($table,$orderfield,$idfield,$id=null,$pos=null,$newpos=null) {
  2. if($pos!=$newpos) {
  3. if($newpos>$pos) {
  4. mysql_query($sql = "UPDATE ".$table." SET ".$orderfield."=".$orderfield."-1 WHERE ".$orderfield."<= '".$newpos."' AND $idfield<>'".$id."'");
  5. mysql_query($sql = "UPDATE ".$table." SET ".$orderfield."=".$orderfield."+1 WHERE ".$orderfield."> '".$newpos."' AND $idfield<>'".$id."'");
  6. } else {
  7. mysql_query($sql = "UPDATE ".$table." SET ".$orderfield."=".$orderfield."-1 WHERE ".$orderfield."< '".$newpos."' AND $idfield<>'".$id."'");
  8. mysql_query($sql = "UPDATE ".$table." SET ".$orderfield."=".$orderfield."+1 WHERE ".$orderfield.">= '".$newpos."' AND $idfield<>'".$id."'");
  9. }
  10. }
  11. if($pos!=$newpos || ($pos==null && $newpos == null && $id==null) ) {
  12. $rs = mysql_query($sql = "SELECT $orderfield,$idfield FROM ".$table." ORDER BY ".$orderfield." ASC");
  13. $p = 0;
  14. while($r=mysql_fetch_array($rs)) {
  15. $p++;
  16. mysql_query($sql = "UPDATE ".$table." SET ".$orderfield."='".$p."' WHERE ".$idfield."= '".$r[$idfield]."'");
  17. }
  18. }
  19. }

以上是关于如何对更改位置字段的行重新排序的主要内容,如果未能解决你的问题,请参考以下文章

python - 如何按python中的因子级别对pandas数据框中的行进行重新排序?

C#:怎样对dataList表格中的行数据按时间降序排列

在angularjs中对表格的行进行排序或重新排列(拖放)

如何使用 Jquery 重新排序 Gridview 行?

MySQL 获取 ORDER BY 编号错误的行位置

BottomNavigationView - 如何避免重新创建片段并重用它们