2013-03-23 199 views
0

我正在通過複製第一個元素將一個元素添加到數組中。然後我只改變第一個元素[0]的某些屬性 - 但(由於某些原因,我不明白)所有元素的屬性(例如[1]),而不僅僅是改變的元素也會改變。設置數組的屬性

代碼:

$this->product->images[] = $this->product->images[0]; 
$file = uniqid().'.png'; 
$this->product->images[0]->file_url = 'images/magick/'.$file; 

此代碼也改變了$這個 - >產品 - >圖像[1] - > FILE_URL爲「圖像/ magick /'.$文件時我只是想改變第一([0])元素。

回答

0

檢查:

$this->product->images[] = clone $this->product->images[0]; 
$file = uniqid().'.png'; 
$this->product->images[0]->file_url = 'images/magick/'.$file; 
+0

完美工作 - 謝謝! – Dzseti 2013-03-23 23:07:43

0

這是因爲$images中的項目是對象(請參閱Objects and references)。所以,你必須使用:

$this->product->images[] = clone $this->product->images[0]; 

但要知道,我不知道你在使用類,所以它可能是你需要一個深克隆在某些情況下,還克隆可以取決於你的對象(見Object Cloning)。