Search code examples
phphtmlcodeigniter-4

How to use if elseif inside table row without making a new row?


I want to make a code that can use if else if inside table row.

But I can't make it ,once I use else if statement inside table row it make a new row by it self.

I expect that it make a new column in the same row

Here's a code

<tbody>
    <?php $i = 1;
    $varpetugas = null;
    $varrealisasi = null;
    ?>

    <?php foreach ($petugas as $k) : ?>
        <tr>
            <?php if ($k['nama_petugas'] != $varpetugas) : ?>
                <th scope="row"><?= $i++; ?></th>
                <td><?= $k['jenis_survey']; ?></td>
                <td>
                    <?= $k['nama_petugas']; ?>
                    <?php $varpetugas = $k['nama_petugas']; ?></td>
                <td><?= $k['target']; ?></td>
                <td><?= $k['realisasi']; ?></td>
                <?php $varrealisasi = $k['realisasi']; ?>
            <?php elseif ($k['nama_petugas'] == $varpetugas) : ?>
                <td>
                    <?= $k['target']; ?>
                </td>
                <td>
                    <?= $k['realisasi']; ?>

                </td>
                <?php $varrealisasi = $k['realisasi']; ?>
                <?php $varpetugas = $k['nama_petugas']; ?>


            <?php endif; ?>
        </tr>
   <?php endforeach; ?>
</tbody>

as you can see what I expected is else if statement show the output in a same row but , here's the result

enter image description here


Solution

  • You do new row (<tr>) every time when loop (next line after foreach).

    But what you want to do is to have it only when condition (<?php if ($k['nama_petugas'] != $varpetugas) : ?>) is true.

    Try this:

    <?php foreach ($petugas as $k) : ?> 
            <?php if ($k['nama_petugas'] != $varpetugas) : ?>
                <?php if ($i > 1) : ?>
                    </tr>
                <?php endif; ?>
                <tr>            
                <th scope="row"><?= $i++; ?></th>
                <td><?= $k['jenis_survey']; ?></td>
                <td>
                    <?= $k['nama_petugas']; ?>
                    <?php $varpetugas = $k['nama_petugas']; ?></td>
                <td><?= $k['target']; ?></td>
                <td><?= $k['realisasi']; ?></td>
                <?php $varrealisasi = $k['realisasi']; ?>
            <?php elseif ($k['nama_petugas'] == $varpetugas) : ?>
                <td>
                    <?= $k['target']; ?>
                </td>
                <td>
                    <?= $k['realisasi']; ?>
    
                </td>
                <?php $varrealisasi = $k['realisasi']; ?>
                <?php $varpetugas = $k['nama_petugas']; ?>
            <?php endif; ?>
    <?php endforeach; ?>
    <?php if ($i > 1) : ?>
        </tr>
    <?php endif; ?>
    

    PS: Why do you have elseif? You can simply do just else. Isn't it?