如何在php和mysql中更改db行位置并维护顺序

时间:2012-06-16 08:16:53

标签: php mysql algorithm

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

所以我在表格中添加了一个位置int列。现在主要问题是改变位置并维持秩序。我一直在摸不着头脑,发现在PHP中使用数组的解决方法,但它是错误的。这是我的方式:选择position作为键,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);

我认为它可以完美地运作但经过一些尝试后,这些职位变得混乱了。我想知道是否有人已经解决了这个问题。 如果是的话我会很感激,不胜感激

感谢您阅读本文

1 个答案:

答案 0 :(得分:0)

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)
        );
    }
}