php - 在设定范围内增加整数

标签 php arrays

如果我想循环遍历一个数组,然后将它们用作循环增量计数器,我该怎么做?

例如我在数组中存储了最多 5 个值。我想循环遍历它们,在第一个循环中我想使用一个特定值,然后在第二个循环中使用另一个特定值。

下面是伪代码,但是如何将第二个数组带入图片中?第一个范围将是动态的和空的,或者最多有 5 个值。第二个将被修复。

$array = array(2,6,8); // Dynamic

$array2 = array(11,45,67,83,99); Fixed 5 values

foreach ($array as $value) {
    // First loop, insert or use both 2 and 11 together
    // Second loop, insert or use both 6 and 45
    // Third loop, insert or use both 8 and 67
}

最佳答案

使用$index => $val:

foreach ($array2 as $index => $value) {
    if ( isset($array[ $index ]) ) {
          echo $array[ $index ]; // 2, then 6, then 8
    }
    echo $value; // 11, then 45, then 67, then 83, then 99 
}

在此处查看实际操作:http://codepad.viper-7.com/gpPmUG


如果您希望它在到达第一个数组末尾时停止,请循环遍历第一个数组:

foreach ($array as $index => $value) {
    echo $value; // 2, then 6, then 8
    echo $array2[ $index ]; // 11, then 45, then 67
}

在此处查看实际操作:http://codepad.viper-7.com/578zfQ

关于php - 在设定范围内增加整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14159367/

相关文章:

php - 是否可以从 Mysql 触发器向 php 传递一个值?

PHP - 强制 eval() 在全局范围内运行?

成功存储在数据库中时的php错误消息

jquery - 将数组传递给 jQuery 选择器

c++ - 用户输入存储在 char 数组中 (C++)

php - 如何在 CodeIgniter 4 的助手中编写数据库查询

php - $post 不适用于 jquery mobile

c - 使用 MPI,当存在连续数组时,用户定义的数据类型是否无用?

c - LLIST *mylist[x] 仍有问题

php - 数组循环问题