【发布时间】:2014-10-30 17:18:25
【问题描述】:
我正在遍历一系列产品,并且对于每次迭代我调用一个函数theFunction
$products = array (
//...
//...
);
$count = count($products);
$i = 0;
foreach ($products as $product) {
theFunction($id, $name, $i);
$i++;
if($i == $count){
// complete
}
}
然后在这个函数中,我有几个带有计数器的其他循环,我需要区分如果它是循环中的第一个会发生什么。为此,我使用$counter,如果为 1,则处理task 2,否则应始终处理task 3
function theFunction( $id, $name, $key ){
$design = Mage::getModel('catalog/category')->load($id);
$collection = $design->getProductCollection();
foreach ($collection as $p) {
// do task 1...
// if success/exists then proceed...
if(file_exists('new_name.jpg')) {
$product = Mage::getModel('catalog/product')->load($p->getId());
$new_array = array( $key => $name.'.jpg' );
$counter = 1;
foreach($new_array as $label => $img){
if($counter === 1 ){
// do task 2
}else{
// do task 3
}
$counter++;
}
$product->save();
}
}
}
此时计数器始终设置为 1 并且永远不会增加,因此它始终在每次迭代时处理任务 2
【问题讨论】:
-
无法复制问题:ideone.com/Q7VBmr