Home > OS >  showing data from foreach loop in column way instead of rows way
showing data from foreach loop in column way instead of rows way

Time:12-15

I try to get the data from database using foreach loop and display them in column way, at the moment i receive them as it appears on this photo

but i need that it appears like this way

| Founders Circle  |  Global Pool |    Universal Pool |  Infinity Pool |  Regional Pool |
|78156 -and input- |1021673-input |  5000000 - input  | 56823 - input  |  0 and input   |
<?php
    foreach( $calculations as $calculation ) {
?>
<table>
    <tr>
        <th>
        <?php echo $calculation['Calculation']['poolname']; ?>
        </th>
    </tr>
    <tr>
        <td>
        <div  id="pool_calc">
            <?php echo $calculation['Calculation']['total_units']; ?>
            <input name="own_pools" type="text" value="" id="own_pools"  maxlength="3" size="4" >
        </div>
        </td>
    </tr>
    <?php 
    }
    ?>
</table>

what is wrong or how can i fix it?

CodePudding user response:

There are more ways, the easiest one for understanding for you is to use two same foreach loops.

<table>
    <tr>
<?php
        foreach( $calculations as $calculation ) {
        // All TH in the first row
?>
            <th>
                <?php echo $calculation['Calculation']['poolname']; ?>
            </th>
<?php 
        }
?>
    </tr>
    <tr>
<?php
        foreach( $calculations as $calculation ) {
            // All TD in the second row
?>
            <td>
                <div  id="pool_calc">
                    <?php echo $calculation['Calculation']['total_units']; ?>
                    <input name="own_pools" type="text" value="" id="own_pools"  maxlength="3" size="4" >
                </div>
            </td>
<?php 
        }
?>
    </tr>
</table>

In your code in the Question you create for each record new table with 2 rows (you had 5 tables in total).

The basic idea is to move <table> outside the loop.

Updated code doing the some, without duplicating foreach loop (saving TDs in variable and echo later).

<table>
    <tr>
<?php
        $tds = '';
        foreach( $calculations as $calculation ) {
        // All TH in the first row
?>
            <th>
                <?php echo $calculation['Calculation']['poolname']; ?>
            </th>

<?php            
            // create TDs code
            $tds .= '
                <td>
                    <div  id="pool_calc">
                        ' . $calculation['Calculation']['total_units'] . '
                        <input name="own_pools" type="text" value="" id="own_pools"  maxlength="3" size="4" >
                    </div>
                </td>
            ';
        }
?>
    </tr>
    <tr>
<?php
        echo $tds;
        // echo TDs in the second row
?>
    </tr>
</table>
  • Related