如果我想循环遍历一个数组,然后将它们用作循环增量计数器,我该怎么做?
例如我在数组中存储了最多 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/