我将问题从MYSQL生成到循环中。我想让question_category在每一行中都不要重复,只在该类别中第一个问题的顶部显示一次?

马上:
问题类别1 Question1(O)(O)(O)
问题类别1 Question2(O)(O)(O)
问题类别2 Question1(O)(O)(O)
问题类别2 Question2(O)(O)(O)

我的目标:
问题类别1
问题1(O)(O)(O)
问题2(O)(O)(O)
问题类别2
问题1(O)(O)(O)
问题2(O)(O)(O)

<?php
// generate active questions from DB
$query = "SELECT * FROM questions where active=1 AND question_sort=1 ORDER BY sort_by";
$result = @mysqli_query($con, $query);
?>
<div class="questions-1">
    <table width="auto" border="0">
        <tr>
            <td></td>
            <td></td>
            <td class="answer_value">0</td>
            <td class="answer_value">1fta</td>
            <td class="answer_value">2</td>
          </tr>
<?php
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    // question body for each question
    $body = $row['question_body'];
    // question id for each question
    $question_id = $row['question_id'];
    // question category for each question
    $question_category = $row['question_category'];
          echo '<tr>
            <td class="question">'.$question_category.'</td>
            <td class="question">'.$body.'</td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="0" ></td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="1" ></td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="2" ></td>
          </tr>';
}
?>
</table></div>

最佳答案

由于您的查询显然返回了已排序的内容,因此特定类别的所有问题都归为一组。

<?php
$currcategory = ""; // Holder to keep track of the current category we are working with.
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    // question body for each question
    $body = $row['question_body'];
    // question id for each question
    $question_id = $row['question_id'];
    // question category for each question
    $question_category = $row['question_category'];
    if ($currcategory !== $question_category) { // The category has changed so lets create a 'header' row.
        $currcatgory = $question_category;
        echo '<tr><td colspan="5">'.$currcategory.'</td></tr>';
    }
          echo '<tr>
            <td class="question">'.$question_category.'</td>
            <td class="question">'.$body.'</td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="0" ></td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="1" ></td>
            <td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="2" ></td>
          </tr>';
}
?>

关于php - 停止从php oop中重复的mysql值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25752883/

10-16 16:32
查看更多