2015-11-05 85 views
0

我有一個foreach循環($ product_image)和一個數組($ newProductData),我試圖做的是將foreach內容($ mediagalleryURLs)放入$ newProductData數組中,我的print_r $ newProductData時,輸出顯示只有最後的foreach元素作爲$ newProductData [「media_gallery」]值,而不是完整的元素,這裏是代碼:PHP Array只顯示最後一個數組項目

<?php 
... 

$resimURLNew = (string) $item->xpath('images/image[@main=1]')[0]; 

foreach($item->images->image as $product_image) { 
    $mediagalleryURLs = $product_image.';'; 
    $mediagalleryURLs = rtrim($mediagalleryURLs, ';'); 
} 

$newProductData = array(
    'sku'    => (string) $item->id, 
    'barcode'   => (string) $item->barcode 
); 

$newProductData['image']  = (string) $resimURLNew; 
$newProductData['small_image'] = (string) $resimURLNew; 
$newProductData['thumbnail'] = (string) $resimURLNew; 
$newProductData['media_gallery'] = $mediagalleryURLs; 

... 
?> 
+0

您將要覆蓋在foreach循環的每次迭代的'$'mediagalleryURLs。 –

+1

@mediagalleryURLs應該是一個數組還是分號分隔的字符串? –

回答

1

您必須追加網址:

foreach($item->images->image as $product_image) { 
    $mediagalleryURLs .= rtrim($product_image) . ';'; 
} 
0

您將要覆蓋的變量時,你應該將元素添加到您的陣列中:

$mediagalleryURLs = array(); 
foreach($item->images->image as $product_image) { 
    $mediagalleryURLs[] = rtrim($product_image.';', ';'); 
} 
0

試試這個,

$newProductData = array(
    'sku'    => (string) $item->id, 
    'barcode'   => (string) $item->barcode 
); 

foreach($item->images->image as $product_image) { 
    $mediagalleryURLs = $product_image.';'; 
    $mediagalleryURLs = rtrim($mediagalleryURLs, ';'); 
    $newProductData['media_gallery'] = $mediagalleryURLs; 
} 

$newProductData['image']  = (string) $resimURLNew; 
$newProductData['small_image'] = (string) $resimURLNew; 
$newProductData['thumbnail'] = (string) $resimURLNew;