php interface implements drag and drop sorting function

List drag and drop sorting is a very common function, but how to deal with the back-end interface is a tangled problem.
How to achieve the highest efficiency?

First analyze a scene, if there are ten pieces of data on a page, the so-called drag and drop is to drag back and forth between these ten pieces of data, but each drag will affect other data
, such as dragging the last piece to the front, then the next nine pieces of data It will automatically move backward, and vice versa, um~~~

First imagine that the sorting number is fixed, as if there are ten chairs, each chair is fixed there, and the person above moves, so that it will not affect the data on other pages
and everyone changes It is also the number of other people's desks and chairs before, so you don't have to think about how much you need to add to where you can rank.

Interface design:

//$ids 这十条数据的id集合,逗号隔开的字符串
//$oldIndex 原始位置,从0开始算
//$newIndex 要拖动的位置
function dragSort($ids,$oldIndex,$newIndex)
{
    //保证查找出来的数据跟前台提交的顺序一致,这里要order by field
    //id 主键 sort 排序值
    $sql =  "select id,sort from 表名字 where id in ($ids) order by field(id, " . $ids . ") ";
    $list =  "这里省略,就是去数据库找嘛";
    //id集合
    $idArr   = [];
    //排序集合
    $sortArr = [];
    foreach ($list as $item) {
        $idArr[]   = $item['id'];
        $sortArr[] = $item['sort'];
    }
    //记录要拖动的id
    $oldValue = $idArr[$oldIndex];
    //删除这个要拖动的id
    unset($idArr[$oldIndex]);
    //插入新的位置,并自动移位
    array_splice($idArr, $newIndex, 0, $oldValue);
    //重新设置排序
    $set = [];
    for ($i = 0; $i < count($idArr); $i++) {
         $set[$i]['id']   = $idArr[$i];
         $set[$i]['sort'] = $sortArr[$i];
     }
    //保存到数据库省略
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324732255&siteId=291194637