我正在使用jQuery DataTables Row Reordering plugin对网页上的测验列表进行重新排序。处理AJAX response并将更改持久保存到数据库的最佳方法是什么(在我的情况下是MySQL)?
目前,我只是从数据库中提取测验列表,将它们传递给执行重新排序的函数,然后循环结果以将测验保存回数据库。这是我的重新排序函数,带有示例测试用例和输出:
<?php
/**
* Reorders a list of quizzes.
* Assumes that the input list of quizzes is in sorted
* order and looks like this:
*
* $quizzes = array(array('id'=>27, 'sort_order'=>1), ...);quiz_id:{$quiz['id']} from: $from to: $to dir: $dir\n";
if($counter === $to) {
$next = $quiz;
} else if(count($quizzes) === $from) {
array_pop($quizzes); // discard
continue;
} else {
$next = array_pop($quizzes);
}
$next['sort_changed'] = ($next['sort_order'] !== $counter);
$next['sort_diff'] = $counter - $next['sort_order'];
$next['sort_order'] = $counter;
$reordered[] = $next;
$counter--;
}
return array_reverse($reordered);
}
?>
示例:
<?php
$quizzes = array(
array('id' => 1, 'sort_order' => 1),
array('id' => 2, 'sort_order' => 2),
array('id' => 3, 'sort_order' => 3),
array('id' => 4, 'sort_order' => 4),
array('id' => 5, 'sort_order' => 5)
);
$from = 4;
$quiz = $quizzes[$from-1];
$to = 1;
$result = reorder($quizzes, count($quizzes), $quiz, $from, $to, 'back');
print json_encode($result);
?>
输出如下:
[{"id":4,"sort_order":1,"sort_changed":true,"sort_diff":-3},
{"id":1,"sort_order":2,"sort_changed":true,"sort_diff":1},
{"id":2,"sort_order":3,"sort_changed":true,"sort_diff":1},
{"id":3,"sort_order":4,"sort_changed":true,"sort_diff":1},
{"id":5,"sort_order":5,"sort_changed":false,"sort_diff":0}]
我是否过度思考这个?有更简单的解决方案吗?