PHP / MySQL remove diuplicate names from a list

时间:2016-03-02 10:47:18

标签: php mysql arrays

We have a MySql table view for the user registered from different districts, with the following columns:

District, City, User_Name

We are displaying the data in tabular form from the db with group by clause.

The mysql query is:

SELECT district, city, count(*) as reg_total FROM tabelname group by district, city;

Then we store the resulting values in two arrays, $district and $Cities and is being displayed with PHP:

<table class="table table-hover table-striped">
    <tbody>
    <?php
        $reg_total = array_sum($data_total);
        $count = 0;
        echo "<tr><td><b>District</b></td><td><b>City</b></td><td><b>Total</b></td></tr>";
        foreach ($Cities as $city)
        {
            echo "<tr><td >$district[$count]</td><td >$city</td><td >$data_total[$count]</td></tr>";
            $count++;
        }

    ?>
    </tbody>
</table>

For example:

District, City, User_Name
A1  B1 U1
A1  B1 U2
A1  B2 U3
A2  B3 U4
A2  B4 U5
A3  B4 U6
A3  B4 U6

What we want to display is, in the first column, we do not want to repeat the District names, for example it should display like this:

District, City, User_Name
A1  B1 U1
    B1 U2
    B2 U3
A2  B3 U4
    B4 U5
A3  B4 U6
    B4 U6

Any solution with plain PHP will be appreciated.

2 个答案:

答案 0 :(得分:3)

只需检查每行获取期间的Distict名称:

<?php
    $link = mysqli_connect('localhost', 'root', '') or die(mysqli_error($link));
    $query = "SELECT * FROM districts ORDER BY District";
    $result = mysqli_query($link, $query) or die(mysqli_error($link));
    print '<table border="1">
        <tr>
            <td>District</td>
            <td>City</td>
            <td>User_Name</td>
        </tr>';
    $tmp = $name = '';
    while ($row = mysqli_fetch_array($result)) {
        if($tmp != $row['District']){
            $name = $row['District'];
            $tmp = $row['District'];
        }else{
            $name = '';
        }
        print '<tr>
             <td>' . $name . '</td>
             <td>' . $row['City'] . '</td>
             <td>' . $row['User_Name'] . '</td>
        </tr>';
    }
    print '</table>';
?>

输出:

enter image description here

答案 1 :(得分:0)

试试这个 -

<?php
    $district = '';
    foreach($resultset as $row)
    {
        if($district != $row->district)
        {
            echo $row->district.' ';
        }
        echo $row->city.' '.$row->username;
        echo '<br/>';
        $district = $row->district;
    }
?>