duanhao8540 2015-12-07 21:01
浏览 20
已采纳

PHP跟踪最后的x次迭代

I have four variables: $one_flag, $two_flag, $three_flag, and $four_flag. I'm using them as flags inside a for loop because I want to keep track of the last four iterations.

$one_flag = 1;
$two_flag = 0;
$three_flag = 0;
$four_flag = 0;

$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);

foreach ($a as $v) {
    if ($one_flag){
        $first_v = $v;
        $one_flag = 0;
        $two_flag = 1;
    }
    if ($two_flag){
        $second_v = $v;
        $two_flag = 0;
        $three_flag = 1;
    }
    if ($three_flag){
        $third_v = $v;
        $three_flag = 0;
        $four_flag = 1;
    }
    if ($four_flag){
        $fourth_v = $v;
        $four_flag = 0;
        $first_flag = 1;
    }
    if ($v == 45){
        # tricky part
        print "The last three v's were: " . $first_v . ", " . $second_v . ", " . $third_v . "
";
    }
}

Right now it prints The last three v's were 1, 1, 1 but it's supposed to print The last three v's were 45, 44, 27. Also, the problem with the code above is I need to know which flag is equal to 1 (what flag we're currently on) so that I can print the correct statement.

For example, when $v == 45, $first_v is suppose to equal to 27; $second_v is suppose to equal to 44; $fourth_v is suppose to equal to 17; and third_v is suppose equal to 45. I'd need to know $three_flag is equal to 1 in order to print out "The last three were $second_flag, $first_flag, $fourth_flag" in that order.

How can I get my loop to work? How do I keep track of the last four iterations?

EDIT: I misspoke. I actually want to print The last three v's were 44, 27, 17

  • 写回答

5条回答 默认 最新

  • duanaidang6197 2015-12-07 21:13
    关注

    I suppose that this is a minimal example and that the real program is more complex. Otherwise, you could just get the length of the array and retrieve the last 3 elements based on it.

    I'd change the approach as follow:

    $f1 = -1;  // Last value read
    $f2 = -1;  // second to last value
    $f3 = -1;
    
    
    $a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
    
    foreach ($a as $v) {
        $f3 = $f2;
        $f2 = $f1;
        $f1 = $v;
        if ($v == 45){
            # tricky part
            print "The last three v's were: " . $f1 . ", " . $f2 . ", " . $f3 . "
    ";
        }
    }
    

    I'm using -1 as an indicator that nothing was assigned to the variable. You should adapt this to your context if needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动