nur1 nur1 - 2 months ago 9
PHP Question

Looping an array in table

I have this code:

<?php

for($i=0; $i<count($data);$i++) {
for($j=0; $j<count($data); $j++){
if($i == $j){
}else{
?>
<th><?php echo $i.",".$j ?></th>
<th><?php echo ("$data[$i]") ?></th>
<th><?php echo ("$data[$j]") ?></th>
<?php
}
}
}
?>


Current result:

0,1 12 13 0,2 12 14 1,0 12 11 1,2 12 13 2,0 13 11 2,1 13 12


Expected result:

0,1 12 13
0,2 12 14
1,0 12 11
1,2 12 13
2,0 13 11
2,1 13 12


Any suggestions?

Answer

Looks you've got the numbers you want being output but you want to introduce line breaks after each row. You're using the <th> element which is part of a table, but I don't see the other table elements. All you need is to put each table row into a <tr> element and wrap the whole thing in a <table> tag.

<table>
<?php

    for($i = 0; $i < count($data); $i++) {
        for($j = 0; $j < count($data); $j++){
            if($i == $j){
            }else{
?>
            <tr>
                <th><?php echo $i . "," . $j ?></th>
                <th><?php echo ("$data[$i]") ?></th>
                <th><?php echo ("$data[$j]") ?></th>
            </tr>
<?php 
            }
        }   
    }
?>
</table>