我有一个 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/