0

Consider a table for example

enter image description here

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

enter image description here

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

3

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

You should switch the code inside else and if statement

1 Comment

Try placing the code <td><td rowspan=... inside the if statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.