如何在php / magento中动态创建数组

时间:2012-08-23 14:40:25

标签: php magento magento-1.7

我尝试过以下代码

<?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包含所有元素,或者只是指出我犯了错误的地方。

2 个答案:

答案 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;