2014-12-23 5 views
0

다른 문서 "Commands"의 임베디드 컬렉션이 들어있는 symfony2 프로젝트에 "Operation"문서가 있습니다. 두 명령의 위치를 ​​바꿔주는 작업을 작성하려고합니다. 내가 컬렉션을 정상적인 PHP 배열로 취급하려고했지만 예상대로 동작하지 않았습니다. Doctrine ArrayColection의 두 요소 교환하기

class Operation 
{ 
    ... 
    /** 
    * The sequence of commands 
    * @MongoDB\EmbedMany(targetDocument="Command") 
    */ 
    protected $commands; 

    public function __construct() 
    { 
     $this->commands = new \Doctrine\Common\Collections\ArrayCollection(); 
     $this->fallbacks = new \Doctrine\Common\Collections\ArrayCollection(); 
    } 

    /** 
    * 
    */ 
    public function swapCommands($index1, $index2) 
    { 
     $temp = $this->commands[$index1]; 
     $this->commands[$index1] = $this->commands[$index2]; 
     $this->commands[$index2] = $temp; 
    } 
    ... 
} 

내가 swapCommands(), 영향을받는 요소는 배열 컬렉션의 바닥에 떨어질 때. 예를 들어 명령이 ['cd', 'ls', touch', 'mv']이라고 가정 해 보겠습니다. 인덱스 0과 1을 바꾸려고하면 [touch', 'mv', 'ls', 'cd']이됩니다. 배열 컬렉션에서 두 요소를 어떻게 바꿀 수 있습니까? 나의 최후의 수단 수동으로 수집 및 add() 각 요소 ... 내가이 일을 발견

+0

스왑 기능이 제대로 작동합니다. .. 명령을 인스턴스화하는 방법을 확인하십시오 (또는 스왑 전에 덤프하십시오) – Matteo

+0

ArrayCollections에서 이것이 올바른지 확신합니까? – ecc

+0

은 더 나은 접근 방법이 아니지만 작동합니다. 몽고 db가없는 로컬 환경에서 코드를 시험해 봅니다. '$ op = new Operation(); $ op-> commands-> add ('cd'); $ op-> commands-> add ('ls'); $ op-> commands-> add ('touch'); $ op-> commands-> add ('mv'); $ op-> swapCommands (0,1); print_r ($ op-> commands-> toArray()); die; – Matteo

답변

0

가장 좋은 방법,하지만 가장 우아한하지를 통과하는 것입니다 :

public function swapCommands($index1, $index2) 
{ 
    $arr = $this->commands->toArray(); 
    $temp = $arr[$index1]; 
    $arr[$index1] = $arr[$index2]; 
    $arr[$index2] = $temp; 

    $this->commands = new \Doctrine\Common\Collections\ArrayCollection(); 
    for ($i=0; $i < count($arr); $i++) { 
     $this->addCommand($arr[$i]); 
    } 
} 
관련 문제