2016-05-20 33 views
-1

我已經搜索過這個,找不到它,它應該很簡單,但現在我被套牢了。原諒我 - 我只待了幾個月。我需要一個計數器內的計數器

我需要一個計數器內的PHP,這樣我配對$ Id1與$ Id2,然後$ Id3,然後$ Id4等,爲一個循環通過,然後爲第二個循環對$ Id2與$ Id3,然後$ Id4,然後$ Id5等我從一個SQL查詢得到Ids,然後我使用他們兩個來運行他們的關係計算,但首先我只需要結構來運行這兩個循環,一個另一個。感謝您的幫助和耐心。

編輯補充什麼,我到目前爲止有:

$collection = []; 

$sql = 'SELECT id, name FROM table';                                                                                       
$result = mysql_query($sql); 


while($row = mysql_fetch_assoc($result)) 

    {   
     $collection[] = $row; 
    } 
     $ct = count($collection); 
     for ($i = 0; $i < $ct; $i++)     
     { 

      $Id1 = $collection[$i]['id'];  
      for ($j = 0; $j < $ct; $j++) 
       { 
        $Id2 = $collection[$j]['id']; 
        if($Id1 != $Id2){ 
        echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>'; 
        } 

       } 

     }   

} 
+0

你不會先試一試,併發布結果嗎?這將大大有助於解釋你的目標。 – ExcellentSP

+0

是的,因爲沒有人知道你在說什麼。編輯了 – AbraCadaver

+0

以包含我的內容。抱歉。 – ngtess

回答

0

如果您擷取您查詢的ID添加到一個這樣的數組:$ids = [1,2,3,4,5,6,7,8];,你可以使用array_chunk對列表,然後移離第一個元素,並重復這個過程直到數組爲空。

while ($ids) {       // repeat until empty 
    $pairs = array_chunk($ids, 2);  // split into pairs 
    foreach ($pairs as $pair) { 
     if (count($pair) == 2) {  // verify that you have a pair (last element will 
             // have only one item when count($ids) is odd) 
      var_dump($pair);   // do something with your pair of IDs 
     } 
    } 
    $remove_first = array_shift($ids); // shift off the first ID 
} 

請注意,使用array_shift這樣會破壞你的輸入數組,所以如果你需要做別的事情與它爲好,使用這種方法之前,做它的一個副本。

相關問題