我有一個數組,我需要複製數組中的第一個項目並對其進行修改。PHP引用數組而不是複製
這是我在做什麼:
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
$firstItem = $QuantityDiscounts[0];
$firstItem['from_quantity'] = 999;
$firstItem['price'] = 999;
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
這是輸出這給了我:
4.870000
10
4.870000
999
當我改變了複製的數組它改變原有數組的值。什麼讓這個更奇怪的是,它只發生在'from_quantity'項目。正如你所看到的'價格'元素保持不變。
我不明白爲什麼會發生這種情況,因爲您可以看到我沒有使用引用。有沒有解釋這種行爲,我錯過了?
一些更多的信息:
如果我第一次原始數組中複製「from_quantity」,所以它使用不同的密鑰這種行爲就會消失。
$QuantityDiscounts[0]['test'] = $QuantityDiscounts[0]['from_quantity'];
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
echo $QuantityDiscounts[0]['test'] . '<br>';
$firstItem = $QuantityDiscounts[0];
$firstItem['from_quantity'] = 999;
$firstItem['test'] = 999;
$firstItem['price'] = 999;
echo $QuantityDiscounts[0]['price'] . '<br>';
echo $QuantityDiscounts[0]['from_quantity'] . '<br>';
echo $QuantityDiscounts[0]['test'] . '<br>';
輸出:
4.870000
10
10
4.870000
999
10
**更新** - 感謝您的幫助迄今爲止
這裏是生成陣列功能。我可以看到在那裏引用了一個引用這個問題的引用。這是否意味着我無法在不更改原始內容的情況下複製和修改'from_quantity'?
protected function formatQuantityDiscounts($specific_prices, $price, $tax_rate, $ecotax_amount)
{
foreach ($specific_prices as $key => &$row)
{
$row['quantity'] = &$row['from_quantity'];
if ($row['price'] >= 0) // The price may be directly set
{
$cur_price = (Product::$_taxCalculationMethod == PS_TAX_EXC ? $row['price'] : $row['price'] * (1 + $tax_rate/100)) + (float)$ecotax_amount;
if ($row['reduction_type'] == 'amount')
$cur_price -= (Product::$_taxCalculationMethod == PS_TAX_INC ? $row['reduction'] : $row['reduction']/(1 + $tax_rate/100));
else
$cur_price *= 1 - $row['reduction'];
$row['real_value'] = $price - $cur_price;
}
else
{
if ($row['reduction_type'] == 'amount')
$row['real_value'] = Product::$_taxCalculationMethod == PS_TAX_INC ? $row['reduction'] : $row['reduction']/(1 + $tax_rate/100);
else
$row['real_value'] = $row['reduction'] * 100;
}
$row['nextQuantity'] = (isset($specific_prices[$key + 1]) ? (int)$specific_prices[$key + 1]['from_quantity'] : -1);
}
return $specific_prices;
}
我只是做了一個phpfiddle並嘗試它,它不是引用我 - http:// phpfiddle。org/main/code/b8g-03e你一定在做別的事情。 –
哪個版本的php?請提供一個完整的代碼,我們可以複製/粘貼到測試 – Asenar
OP可能是這樣做的: http://phpfiddle.org/main/code/naj-0gu – Kaii