我尝试过以下代码
<?php
foreach ($_wishlistitemCollection as $_wishlistitem):
$_product = $_wishlistitem->getProduct();
$imgpath = $this->helper('catalog/image')->init($_product, 'small_image');
$physpaths = array($imgpath);
endforeach;
?>
<?php
for ($i = 0; $i < 5; $i++) {
echo $physpaths[$i];
}
?>
没有错误,但问题是它不会显示数组$physpaths
中的所有元素。
请帮助我如何确保$physpaths
包含所有元素,或者只是指出我犯了错误的地方。
答案 0 :(得分:4)
如此接近;)
<?php
$physpaths = array();
foreach ($_wishlistitemCollection as $_wishlistitem):
$_product = $_wishlistitem->getProduct();
$imgpath = $this->helper('catalog/image')->init($_product, 'small_image');
$physpaths[] = $imgpath;
endforeach;
?>
<?php
for ($i = 0; $i < 5; $i++) {
echo $physpaths[$i];
}
?>
答案 1 :(得分:1)
为了在新索引处向数组附加值,您应该使用array_push()
或[]
:
<?php
foreach(...) :
.
.
.
// use this
$physpaths[] = $imgpath;
// or this
array_push($physpaths, $imgpath);
// NOT BOTH
endforeach;
然后使用echo
而不是循环遍历每个数组索引并使用var_dump()
:
echo "<pre>";
var_dump($physpaths);
echo "</pre>";
PROTIP:您应该在$physpaths
之前将foreach
初始化为数组。
$physpaths = array();
foreach(...):
.
.
.
endforeach;