如何在 php 和 mysql 中更改数据库行位置并保持顺序


How to change db row position and maintain order in php and mysql

我有一个PHP项目,我一直在使用Doctrine 1.2.4,mysql和Zend(与问题无关)。 有一个新的要求,从管理面板中,可以按位置更改团队成员在团队页面上的外观。

所以我在表格中添加了一个位置 int 列。现在的主要问题是改变仓位并维持秩序。我一直在挠头,并在 php 中使用数组找到了解决方法,但它有问题。这是我的方法:选择位置作为键和 id 作为数组的值,然后对该数组进行重新排序,并根据重新排列的数组重新更新表。这是我的代码:

//here i use string as my id to be able to view the changes .  
//you can swap to this:
  $anarray = array("23", "12", "4", "6", "2");
//$anarray = array("car", "dog", "cow", "cup", "plane");
var_dump($anarray);
function preserveSort($oldposition, $newposition, $arraytosort) {
  // this assumes that there is no zero in position
  $oldposition--;$newposition--;
  $indice = $newposition - $oldposition;
  $tmpNewPosistionData = $arraytosort[$oldposition];
  if ($indice > 0) {
      for ($i = $oldposition; $i < $newposition; ++$i) {
          echo $i . "<br/>";
          $arraytosort[$i] = $arraytosort[$i + 1];
      }
  } else {
      for($i=$oldposition;$i >$newposition; $i--){
          echo $i."<br/>";
          $arraytosort[$i] = $arraytosort[$i-1];        
      }
  }
  $arraytosort[$newposition] = $tmpNewPosistionData;
  var_dump($arraytosort);
}
echo "<br/>";
echo "changing position 1 to 4 <br/>";
preserveSort(1, 4, $anarray);

我认为它可以完美地工作,但经过一些尝试,位置变得混乱。我想知道是否有人已经解决了这个问题。如果是,我几乎没有帮助,将不胜感激

感谢您阅读本文

function move_element($input, $from, $to) { // I suggest $input as first paramter, to match the PHP array_* API
    // TODO: make sure $from and $to are within $input bounds
    // Assuming numeric and sequential (i.e. no gaps) keys
    if ($from == $to) {
        return $input;
    } else if ($from < $to) {
        return array_merge(
            array_slice($input, 0, $from),
            array_slice($input, $from +1, $to - $from),
            array($input[$from]),
            array_slice($input, $to +1, count($input) - $to)
        );
    } else if ($from > $to) {
        return array_merge(
            array_slice($input, 0, $to),
            array($input[$from]),
            array_slice($input, $to, $from - $to),
            array_slice($input, $from +1, count($input) - $from)
        );
    }
}