简体   繁体   中英

PHP while loop dynamic rowspan

Consider a table for example

在此处输入图片说明

using these table I just wanted to print a table like these by adding rowspan to item id 1002.

在此处输入图片说明

Here is my PHP code

$temp_val = '';
$counter = 1;
$sql_sel = mysqli_query($con,"select * from item_table");
while($res_sel = mysqli_fetch_array($sql_sel)){

    if($temp_val == $res_sel['item_id']){
        $counter++;
        echo "<tr></tr>";
    }
    else{
       echo "<tr><td rowspan='".$counter."'>".$res_sel['item_id']."</td></tr>"; 
    }

    $temp_val = $res_sel['item_id'];

}
echo "</table>";

it's not correct, it's adding rowspan to item id 1003

You can't do like this because when you create the first row then you have to decide how much will this column can span so you have to get the count of the similar ids first to achieve it. I am just giving you and idea how it can work with and array like you database provides.

<?php

// Array comming from database
$databaseValues = [
    [
        'item_id'=>'1001',
        'item_color'=>'black',
    ],
    [
        'item_id'=>'1002',
        'item_color'=>'blue',
    ],
    [
        'item_id'=>'1002',
        'item_color'=>'green',
    ],
    [
        'item_id'=>'1003',
        'item_color'=>'red',
    ]
];

// Creating an array as per the need for the table
$arrayForTable = [];
foreach ($databaseValues as $databaseValue) {
    $temp = [];
    $temp['item_color'] = $databaseValue['item_color'];
    if(!isset($arrayForTable[$databaseValue['item_id']])){
        $arrayForTable[$databaseValue['item_id']] = [];
    }
    $arrayForTable[$databaseValue['item_id']][] = $temp;
}

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<table border="1">
    <?php foreach ($arrayForTable as $id=>$values) :
        foreach ($values as $key=>$value) :?>
    <tr>
        <?php if($key == 0) :?>
        <td rowspan="<?= count($values)?>"><?= $id?></td>
        <?php endif;?>
        <td><?= $value['item_color']?></td>
    </tr>
    <?php endforeach;
    endforeach; ?>
</table>

</body>
</html>

Hope this will be helpfull for you

您应该在elseif语句中切换代码

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