为数组分配一个新的索引将导致创建一个新的数组


Assigning a new Index to an array causes a new array creation?

我正在使用OpenCart,并将这样的代码添加到控制器中,以向用户显示所有制造商:

  $this->load->model("catalog/manufacturer");
  $manufacturers = $this->model_catalog_manufacturer->getManufacturers();
  $allbrands = array();
  foreach ($manufacturers as $brand)
  {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
    $allbrands[] = $brand;
  }
  $this->data["manufacturers"] = $allbrands;

它工作得很好,但我之前的代码没有工作,下面是:

  $this->load->model("catalog/manufacturer");
  $manufacturers = $this->model_catalog_manufacturer->getManufacturers();
  $allbrands = array();
  foreach ($manufacturers as $brand)
  {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
  }
  $this->data["manufacturers"] = $manufactures;

我想的是数组是对象,所以它们指向引用,所以如果我改变$brand变量,那么$manufacturers也会有数组有"url"作为索引,但没有工作,PHP抱怨它没有任何"url"索引。

给数组分配一个新的索引会导致它在堆中使用新对象重新创建,或者它扩展了当前对象在堆中的位置?

有什么想法,可能会发生什么?

foreach [docs]正在创建数组值的副本:

为了能够直接用&修改$value之前循环中的数组元素。在这种情况下,值将通过引用赋值。

即使在foreach循环之后,$value和最后一个数组元素的引用仍然存在。建议使用unset()销毁。

这个应该可以工作:

foreach ($manufacturers as &$brand) {
    $brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
}
unset($brand);

foreach创建对象的临时副本。在循环中修改foreach中引用的数组不是一个好主意。

应该在循环内部使用指针进行修改。

这是一个从文档中复制的例子。

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>