doulin6448 2014-10-30 17:18
浏览 21

PHP - 计数器为每个循环不更新[关闭]

I am looping through an array of products and for each iteration i call a function theFunction

$products = array (
    //...
    //...
);
$count = count($products);

$i = 0;
foreach ($products as $product) {
    theFunction($id, $name, $i);
    $i++;
    if($i == $count){
        // complete
    }
}

Then inside this function i have a couple of other loops with a counter whereby i need to differentiate what happens if it is the first in the loop. To do this I use $counter and if it is 1 then it processes task 2 otherwise it should always process 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();

        }

    }

}

At the moment the counter is always set at 1 and never increases so it always processes task 2 on each iteration

  • 写回答

2条回答 默认 最新

  • douyi4991 2014-10-30 17:24
    关注

    $counter is a local variable within the function, being created only within the function, and will be destroyed when the function returns.

    I suggest passing the counter in as a parameter, and then returning it, allowing you to retain the value

    eg in your function definition:

    function theFunction( $id, $name, $key, $counterValue ){
        //stuff
        return $counterValue;
    }
    

    And then when calling the function

    $counter = theFunction($id, $name, $i, $counter);
    

    Don't forget to set $counter = 0; BEFORE your main (not in the function) foreach loop

    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算