Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在关键位置将多个项目插入数组_Php_Arrays - Fatal编程技术网

Php 在关键位置将多个项目插入数组

Php 在关键位置将多个项目插入数组,php,arrays,Php,Arrays,在我的cart类中,我有一个循环: 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函数中,它

在我的cart类中,我有一个循环:

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_拼接($this->items,$position,0,array($newItem))

这是可行的,但问题是这些东西也没有放在我想要的地方。这很难解释,但希望有人能理解

例如,让我们假设$items数组由以下部分组成:
数组('a','b','c','d')

我的结局是:

数组('a','a2','b2','c2','b','c','d')

但我想要的是:
数组('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++;
}

输出:

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"
}

您可以使用附加变量来存储重复数以增加索引

$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++;
}

输出:

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"
}

@ProfessorAbronsius
$this->items
是一个类类型的数组
CartItems
仅供参考-
“如果替换不是数组,它将被类型转换为一(即(数组)$replacement)。这可能会导致在使用对象或空替换时出现意外行为。”
@ProfessorAbronsius
$this->items
是一个类类型的数组
CartItems
仅供参考-
“如果替换不是数组,它将被类型转换为一(即(数组)$replacement)。这可能会导致在使用对象或空替换时出现意外行为。”
这真的很简单和聪明。谢谢这真的很简单和聪明。谢谢