在数组的关键位置插入多个项



在我的购物车类中有一个循环:

foreach($this->items as $key => $item) {
$duplicate = clone $item;
$duplicate->price = 0;
$duplicate->dynamic = 1;
// Duplicate new item to cart
$this->AddItem($duplicate, $key+1);
}

AddItem函数中,它这样做:array_splice($this->items, $position, 0, array($newItem));

它工作,但问题是项目没有到我想要它们的地方。这将是棘手的解释,但希望有人能理解。

例如,$items数组由以下元素组成:array('a', 'b', 'c', 'd')

我结束了:

array('a', 'a2', 'b2', 'c2', 'b', 'c', 'd')

但是我想要的是:array('a', 'a2', 'b', 'b2', 'c', 'c2', 'd')

因为$key的值在foreach循环中没有改变,它将其插入旧$this->items数组的位置$key。但是我希望新条目在原始条目之后复制。我希望这是有意义的。

您可以使用一个额外的变量来存储副本的数量,以增加索引。

$dupes = 0;
foreach ($this->items as $key => $item) {
$duplicate = clone $item;
$duplicate->price = 0;
$duplicate->dynamic = 1;
// Duplicate new item to cart
$this->AddItem($duplicate, $key + 1 + $dupes);
$dupes++;
}

查看实际示例

class Test 
{
private $items = ['a','b','c','d'];
public function dup()
{
$dupes = 0;
foreach ($this->items as $key => $item) {
$this->addItem($item . '2', $key + 1 + $dupes);
$dupes++;
}
}
private function addItem($newItem, $position) 
{
array_splice($this->items, $position, 0, array($newItem));  
} 
public function dump() 
{
var_dump($this->items);
}
}

$test = new Test();
$test->dup();
$test->dump();

输出:

array(8) {
[0]=>
string(1) "a"
[1]=>
string(2) "a2"
[2]=>
string(1) "b"
[3]=>
string(2) "b2"
[4]=>
string(1) "c"
[5]=>
string(2) "c2"
[6]=>
string(1) "d"
[7]=>
string(2) "d2"
}

最新更新