2015-11-05 128 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;