检查 while 循环中的相同行,并将它们放在单独的表中


Check for same rows in a while loop and put them in a separate table

我想先检查所有相等的行,然后将它们放入单独的表中。

这是我到目前为止所做的:

table1
    |   id  |   name    |
    |   1   |   JUS     |
    |   1   |   NUM     |
    |   2   |   SET     |

/**
 * this is the the query for retrieving the data
 * from table1
 */
$query="SELECT 
            id,
            name
        FROM 
            table1
        order by 
            id";
$results=$db->query($query);
$previous='';
while($row=mysqli_fetch_assoc($results)){
    $id=$row['id'];
    $name=$row['name'];
    if($id==$previous){
        /**
         * This is where i am stucked up
         */
        $current='';
    }
    $previous=$id;
}

我想将 1 作为值的 id 获取到一个 html 表中,如下所示

    first html table
    ID      |   1   |   1   |
    Name    |   JUS |   NUM |

并将 ID 2作为值获取到另一个 HTML 表中。因此,我们将获得单独的表如果id不同:

  second html table
    ID      | 2     |
    Name    | SET   |

任何关于如何去做的想法都是值得赞赏的。

您可以先将它们收集到一个容器中,使用 id s 作为您的键,以便将它们组合在一起。之后,只需相应地打印它们:

$data = array();
while($row = $results->fetch_assoc()){
    $id = $row['id'];
    $name = $row['name'];
    $data[$id][] = $name; // group them
}
foreach($data as $id => $values) {
    // each grouped id will be printed in each table
    echo '<table>';
    // header
    echo '<tr>';
        echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
    echo '</tr>';
    echo '<tr>';
    echo '<td>Name</td>';
    foreach($values as $value) {
        echo "<td>$value</td>";
    }
    echo '</tr>';
    echo '</table><br/>';
}

如果这些字段就是这样,这将起作用,如果你需要更动态的东西,你需要另一个维度,而不仅仅是推送name,你需要推送整行:

$results = $db->query('SELECT id, name, age FROM table1');
$data = array();
while($row = $results->fetch_assoc()){
    $id = $row['id']; unset($row['id']);
    $data[$id][] = $row; // group them
}
$fields = array('name', 'age');
foreach($data as $id => $values) {
    // each grouped id will be printed in each table
    echo '<table>';
    // header
    echo '<tr>';
        echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
    echo '</tr>';
    foreach($fields as $field) {
        // construct td
        $temp = '';
        echo "<tr><td>$field</td>";
        for($i = 0; $i < count($values); $i++) {
            $temp .= '<td>' . $values[$i][$field] . '</td>';
        }
        echo $temp; // constructed td
        echo '</tr>';
    }
    echo '</table><br/>';
}