我在symfony2项目中有一个文档"操作",其中包含其他文档"命令"的嵌入式集合。我正在尝试编写一个交换两个命令位置的操作。我试图将集合视为普通的 PHP 数组,但行为与预期不符。
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()
每个元素......
我找到的最好的方法,但不是最优雅的:
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]);
}
}