php - 在多个 for 循环中不断计数

标签 php mysql for-loop

我在一个循环中有一个循环,如下所示:

//stuff here to determine what $my_var will be
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for ($y = 1; $y <= $anothervar; $y++) {
        //help needed in here
        echo $y; //makes it so count starts over each time it goes around
    }
}

my_var 将循环一定次数,但并不总是相同的次数。

内循环也是一个随机数。

输出可能如下所示:

1
    1,2
2
3
4
5
6
    1,2,3

所以在第一个主循环中,内部循环发生了两次。在第6个主循环中,内循环发生了3次。

我想做的是内部循环每次都从 1 开始,我希望它继续计数。所以我希望输出是这样的:

1
    1,2
2
3
4
5
6
    3,4,5

假设第三个主循环中有一些内部循环,我们将其设为 4 个内部循环,那么输出应如下所示:

1
    1,2
2
3
    3,4,5,6
4
5
6
    7,8,9

如何在循环中进行连续计数?

编辑

这是最终的工作结果:

//stuff here to determine what $my_var will be
$y = 1;
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for (; $y <= $anothervar; $y++) {
        //help needed in here
        echo $y; //this now continues to count up instead of starting over each main loop
    }
    $y = 1;
}

最佳答案

$x = 0;
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for ($y = 1; $y <= $anothervar; $y++) {
        $x++;
        echo $x; // now x is incremented every inner loop by 1
    }
}

刚刚更改了第一个代码示例的 3 行。

关于php - 在多个 for 循环中不断计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353916/

相关文章:

MYSQL UPDATE SET 在同一列上但具有多个 WHERE 子句

php - 按列值对 mySQL 结果进行排序

mysql - 使用多个表连接或多个选择编写 MySQL 查询

php - PDO - 从事务中检索变量值?

vba - "Invalid Next Control Variable Reference"VBA Excel 2003 出错

Java:for 循环使用 i

java - 添加两个自己类型的列表

php - 将 POST 数组插入到 mySql 表的多行中时出现问题

php - 附加 where 子句

php - UTF 8 编码在 PHP 中无法正常工作