我怎样才能将这些变成4个2脚的组?

时间:2013-12-12 00:28:29

标签: php

所以这是我的代码,它从数据库中获取人员列表,并将他们与合作伙伴分组列出。在这些组中,人员的用户ID不能出现在同一行中两次。一切正常,我只是想知道如何使每组回应4人而不是2人。

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>';
    }
}

1 个答案:

答案 0 :(得分: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>';
    }

}