简体   繁体   中英

How can i merge Rows of An HTML table fetched from Mysql

I have a MySQL database for a website am building, i have displayed contents of a table in the MySQL database on my page using the PHP code shown below. What i wanted to know was if there was a way to Merge rows of a column with the same value.

note: i don't want the changes to occur in the database but just on the html table displayed on the page
here is the code i used

$arr = array();
while($row = mysql_fetch_row($result)) {
    if (empty($arr[$row[0]])) $arr[$row[0]] = array();
    $arr[$row[0]] [$row[1]] [$row[2]] [$row[3]] [$row[4]] [$row[5]] [$row[6]][] = $row[7];

}
foreach ($arr as $key => $subordinatearr) {
    echo '<tr>';
    echo '<td rowspan="', count($subordinatearr), '">', $key, '</td>';
    echo '<td>', $subordinatearr[0], '</td>';
    echo '<td>', $subordinatearr[1], '</td>';
    echo '<td>', $subordinatearr[2], '</td>';
    echo '<td>', $subordinatearr[3], '</td>';
    echo '<td>', $subordinatearr[4], '</td>';
    echo '<td>', $subordinatearr[5], '</td>';
    echo '<td>', $subordinatearr[6], '</td>';

    if (count($subordinatearr) > 1) {
        for ($i = 1; $i < count($subordinatearr); $i++) {
            echo '</tr><tr><td>', $subordinatearr[$i], '</td>';
        }
    }
    echo '</tr>';
}

Please change this script to

while($row = mysql_fetch_row($result)) {
    echo "<tr>";           
    echo "<td>".$row['Location']."</td>";  
    echo "<td>".$row['Vessel ']."</td>"; 
    echo "</tr>";
 }

I did not understand this part clearly - "Merge rows of a column with the same value." If you don't want to show duplicate records of a column, you can do it in two ways -

Option 1

Keep the value of specific column in an array. Before displaying that column check if the value exists in the array using is_array(). If exists, then skip, otherwise show and add into the array.

Option 2

While making the query, use DISTINCT(col_name) to get only the unique values.

Store the result in an array.

$arr = array();
while($row = mysql_fetch_row($result)) {
    if (empty($arr[$row[0]]) $arr[$row[0]] = array();
    $arr[$row[0]][] = $row[1]; 
}

Then put the array using rowspan like as follows:

foreach ($arr as $key => $subordinatearr) {
    echo '<tr>';
    echo '<td rowspan="', count($subordinatearr), '">', $key, '</td>';
    echo '<td>', $subordinatearr[0], '</td>';
    if (count($subordinatearr) > 1) {
        for ($i = 1; $i < count($subordinatearr); $i++) {
            echo '</tr><tr><td>', $subordinatearr[$i], '</td>';
        }
    }
    echo '</tr>';
}

If data is too big, this may cause an memory error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM