Qammar Feroz
Qammar Feroz

Reputation: 718

PHP / MySQL remove diuplicate names from a list

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.

Upvotes: 0

Views: 82

Answers (2)

Ganesh Gadge
Ganesh Gadge

Reputation: 410

Try this -

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

Upvotes: 0

mitkosoft
mitkosoft

Reputation: 5316

Just check what is Distict name during each row fetch:

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

Output:

enter image description here

Upvotes: 3

Related Questions