浏览文章
文章信息
PHP7.4双循环引用内存地址Bug
13781
示例代码:
foreach ($data as &$attr) {
foreach ($attr as &$p) {
$pd = $repository->get($p['sku'], false, $storeId);
$p['price'] = $pd->getPrice();
$p['image'] = $imageHelper
->init($pd, 'product_thumbnail_image')
->resize($this->imageH, $this->imageW)
->getUrl();
$stockQty = $this->productService->getCurrentWebsiteStockSaleableQty($pd);
$p['stock'] = $stockQty;
$p['website'] = $website_id;
$p['website_name'] = $pd->getStore()->getWebsite()->getName();
}
}&$attr后再在第二层循环&$p
它将不释放地址指针,而是在数组最后一个直接带上&array(,以下是问题返回数据
数据响应查看
<pre>array(6) {[0]=>array(12) {["sku"]=>string(33) "max-size-tomoto-mobile-64G-yellow"["product_id"]=>string(2) "17"["attribute_code"]=>string(5) "color"["value_index"]=>string(1) "4"["super_attribute_label"]=>string(5) "Color"["default_title"]=>string(6) "yellow"["option_title"]=>string(6) "yellow"["price"]=>string(10) "100.000000"["image"]=>string(119) "http://dev.trustonlines.aiweline.com/pub/media/catalog/product/cache/ca8bf164d8b76f05cead76a912ea4f6d/t/i/timg_2__2.jpg"["stock"]=>float(9925)["website"]=>string(1) "1"["website_name"]=>string(12) "Main Website"}......[5]=>&array(12) {["sku"]=>string(31) "max-size-tomoto-mobile-128G-red"["product_id"]=>string(2) "17"["attribute_code"]=>string(5) "color"["value_index"]=>string(1) "5"["super_attribute_label"]=>string(5) "Color"["default_title"]=>string(3) "red"["option_title"]=>string(3) "red"["price"]=>string(10) "128.000000"["image"]=>string(144) "http://dev.trustonlines.aiweline.com/pub/media/catalog/product/cache/ca8bf164d8b76f05cead76a912ea4f6d/u/_/u_3163633005_17752850_fm_26_gp_0_3.jpg"["stock"]=>float(127)["website"]=>string(1) "1"["website_name"]=>string(12) "Main Website"}}<pre>引发最后一个带上地址指针
[5]=>&array(12)&array
解决:
方式一、将内循环的&$p的地址引用去掉
方式二、修改代码为
foreach ($data as &$attr) {
foreach ($attr as $key=>$p) {
$pd = $repository->get($p['sku'], false, $storeId);
$p['price'] = $pd->getPrice();
$p['image'] = $imageHelper
->init($pd, 'product_thumbnail_image')
->resize($this->imageH, $this->imageW)
->getUrl();
$stockQty = $this->productService->getCurrentWebsiteStockSaleableQty($pd);
$p['stock'] = $stockQty;
$p['website'] = $website_id;
$p['website_name'] = $pd->getStore()->getWebsite()->getName();
$attr[$key] = $p;
}
}