2013-01-04 73 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)