2012-06-16 6 views
3

Doctorrine 1.2.4, mysql 및 Zend (문제와 관련 없음)를 사용하여 PHP 프로젝트를 작성했습니다. 관리자 패널에서 팀 페이지의 위치에 따라 팀 구성원의 모양을 변경할 수있는 새로운 요구 사항이있었습니다.db 행 위치를 변경하고 php 및 mysql에서 순서를 유지하는 방법

그래서 테이블에 위치 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); 

내가 그것을 완벽하게 일한 수 있다고 생각하지만, 일부 시도 후 위치가 혼합지고 : 여기 내 코드입니다. 이미이 문제를 해결 한 사람이 있는지 궁금합니다. 그래 난 약간의 도움이 많은이

답변

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) 
     ); 
    } 
} 
를 읽는

감사를 평가한다면

관련 문제