2013-01-04 47 views
2

如果我想循环访问一个数组,然后将它们用作循环递增计数器,我该怎么做?设置范围内的递增整数

E.g.我有多达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 
} 
+2

你的意思2和11 togheter? – Shoe

+0

'foreach($ array as $ key => $ value)'。然后'$ array2 [$ key]' – SDC

+0

是的 - 没错 - 错字,谢谢。 – Dan

回答

2

使用$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

0

确定两个阵列的最小长度。

然后将您的索引i从1循环到最小长度。

现在你可以使用两个数组的i个元素

0

这是我想你想:

foreach($array as $value){ 
    for($x = $value; $array[$value]; $x++){ 
     //Do something here... 
    } 
} 
1

这里有一个清洁,简单的解决方案,即不采用无用和重型非标准库:

$a = count($array); 
$b = count($array2); 
$x = ($a > $b) ? $b : $a; 
for ($i = 0; $i < $x; $i++) { 
    $array[$i]; // this will be 2 the first iteration, then 6, then 8. 
    $array2[$i]; // this will be 11 the first iteration, then 45, then 67. 
} 

我们只是用$i认主for循环里面的两个数组的相同位置为了一起使用它们。主要的for循环将迭代正确的次数,以便这两个数组都不会使用未定义的索引(导致通知错误)。

1

你可以试试这个 -

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

} 
0

您可以使用MultipleIterator

$arrays = new MultipleIterator(
    MultipleIterator::MIT_NEED_ANY|MultipleIterator::MIT_KEYS_NUMERIC 
); 
$arrays->attachIterator(new ArrayIterator([2,6,8])); 
$arrays->attachIterator(new ArrayIterator([11,45,67,83,99])); 

foreach ($arrays as $value) { 
    print_r($value); 
} 

会打印:

Array ([0] => 2 [1] => 11) 
Array ([0] => 6 [1] => 45) 
Array ([0] => 8 [1] => 67) 
Array ([0] => [1] => 83) 
Array ([0] => [1] => 99) 

如果你想让它需要两个阵列有一个值,将标志更改为

MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC 

那么这将给

Array ([0] => 2 [1] => 11) 
Array ([0] => 6 [1] => 45) 
Array ([0] => 8 [1] => 67)