2013-12-12 36 views
0

所以這是我的代碼,它需要一個來自數據庫的人列表,並將他們與他們的合作伙伴分組。在這些組中,人員的用戶標識不能在同一行中出現兩次。一切正常,我只是想知道如何使它呼應4人,每組僅與2我怎樣才能把它們變成2個4的腳背組?

if ($result = $mysqli->query("SELECT * FROM performers")) { 
printf("Found %d rows.\n", $result->num_rows); 

$rows = array(); 

while ($row = $result->fetch_array()) { 
    foreach ($row as $key => $col) { 
     unset($row[$key]); 
     $row[strtolower($key)] = $col; 
    } 
    $rows[] = $row; 
} 

$current = null; 
$count = 1; 
while (! empty($rows)) { 
    if ($current) { 
     $current_performers = array($current['performerid_1'], $current['performerid_2']); 
     $found = false; 
     foreach ($rows as $key => $row) { 
      if (! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) { 
       $found = $key; 
       break; 
      } 
     } 

     if ($found !== false) { 
      echo '<li>', $rows[$found]['performance_id'], ': ', $rows[$found]['perf_name_1'], ' - ', $rows[$found]['perf_name_2'], '</li>'; 
      unset($rows[$key]); 


     } 

     else { 
      echo ''; 
     } 

     echo '</ul><hr />'; 

     $current = null; 
    } else { 
     $current = array_shift($rows); 
     echo '<h3>Group ', $count+, '</h3>'; 
     echo '<ul>'; 
     echo '<li>', $current['performance_id'], ': ', $current['perf_name_1'], ' - ', $current['perf_name_2'], '</li>'; 
    } 
} 
+0

你是指兩個合作伙伴,還是你的意思是說夥伴關係被4個團隊所取代? – Barmar

+0

可以說你有9個條目(1個條目是1個合夥,2個人)。編號看起來有3個組,每個組包含3個條目,在這些組內沒有任何個人ID可以重複。 –

+0

我以爲你說的是​​4人組,不是3人。 – Barmar

回答

0

我想這應該這樣做,但我沒有測試過(除了驗證語法),因爲我不沒有任何樣本數據。

$group_size = 4; 
$current_performers = array(); 
$current_size = 0; 
$count = 1; 
while (!empty($rows)) { 
    if ($current_size == $group_size) { // End previous group 
     echo '</ul><hr>'; 
     $current_performers = array(); 
     $current_size = 0; 
    } 
    if ($current_size == 0) { 
     echo '<h3>Group ', $count++, '</h3>'; 
     echo '<ul>'; 
    } 
    $found = false; 
    foreach ($rows as $key => $row) { 
     if (! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) { 
      $found = true; 
      array_push($current_performers, $row['performerid_1'], $row['performerid_2']); 
      $current_size++; 
      echo '<li>', $row['performance_id'], ': ', $row['perf_name_1'], ' - ', $row['perf_name_2'], '</li>'; 
      unset($rows[$key]); 
      break; 
     } 
    } 

    if (!$found) { 
     // Force a new group to start 
     $current_size = $group_size; 
    } 
    // If we have an unfinished group, finish it 
    if ($current_size) { 
     echo '</ul><hr>'; 
    } 

} 
+0

我在查詢後刪除了我的代碼並添加了你的代碼但無法獲得任何東西,所有顯示的是一個發現的18行後面的空白空間。 –

+0

你已經做了哪些調試來試圖使其工作?就像我說的,我無法測試它,因爲我沒有任何數據。 – Barmar

+0

我使用了18行和列的dtabase,它們與上面所寫的信息匹配,我在查詢後刪除了我的代碼並將其放入。有沒有其他方法可以嘗試? –

相關問題