php - 如何更改数据库行位置并维护 php 和 mysql 中的顺序

标签 php mysql algorithm

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

所以我在表中添加了一个 position 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);

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

感谢阅读本文

最佳答案

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

关于php - 如何更改数据库行位置并维护 php 和 mysql 中的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11061853/

相关文章:

php - 我想重新设计xml结构

php - 为开发制作 MySQL 数据库副本

php - 在 php 中运行两个选择查询并将其编码为 json 格式?

java - 在 Java 中使用循环的数字模式

php - 如果在发送 "readfile"的文件时我修改了文件,会不会下载失败?

php - 用元素替换每个字符

javascript - 仅在服务器上使用 javascript 将 HTML 表格导出到 Excel 时出错

php - php mysql的查询错误有问题

algorithm - KMP模式查找算法

algorithm - 最短路径,2 个权重函数