Draw dynamic table in php

0

I have the following array

$arreglo=[1,2,3,4,5..50]

I want to show them in a table, but that the table is of 10 columns type like this:

1   2  3  4  5  6  7  8  9 10
11 12 13 14 15 16 17 18 19 20
etc...

The number of rows depends on the size of the array divided by 10, rounded to the largest, for example, if I have 25 data in the array (hence 25 positions) then the number of rows would be 3, I have this code, but I shows only the top 10 positions and not the rest

for($j = 0; $j < $rows;){
     $html2.='<tr>';
     for($k = 0;$k < 10; $k++){
          $html2.='<td style="border: 1px solid #666;">Caja#'.($j+1).'<br>'.$datos[$j].'</td>';
          $j++;
          if($j==$tama){ //Si el dato no tiene las 10 cajas minimas para el for
            break;
             }
            }
    $html2.='</tr>'; 

I have for example I have 12 boxes

but when it comes to wanting to show them, it shows me only 10

How can I resolve the error in that code?

    
asked by Baker1562 06.06.2018 в 07:25
source

2 answers

0

I see the problem in that you are increasing the variable $ j within the k loop, then when you exit the k loop, $ j no longer has the value that it should have, if not a closest value to k. You must use a counter, but different from those that carry the loops, otherwise it will not work, and with this you need a for or while loop to traverse the array until the end.

Greetings

    
answered by 06.06.2018 в 11:23
0

Scroll through the data array and check when you want to open or close a row. It is a way to do it with a single loop. Example with an array of 10 elements to show in rows of 5:

$datos = array(1,2,3,4,5,6,7,8,9,10);
$datos_x_fila = 5;

echo "<table>";
for ($i=0; $i<count($datos); $i++) {
    if ($i == 0 ) { //primera fila
        echo "<tr>";
    }

    //Rellenamos columnas
    echo '<td style="border: 1px solid #666;">Caja#'.($i+1).'<br>'.$datos[$i].'</td>';

    if (($i+1) % $datos_x_fila == 0 && $i>0) {
        if ($i == count($datos)) { //última fila
            echo "</tr>";
        } else { //quedan más filas
            echo "</tr><tr>";
        }

    }
}
echo "</table>";

If you want to do it with two loops, you must take into account in which row you are at the time of going through the data, since the first row will cross the first 5 data in my case, the second the next 5, etc.

$n_rows = ceil(count($datos)/$datos_x_fila);
echo "<table>";

$counter = 0;
for ($r=0; $r<$n_rows; $r++) { 
    echo "<tr>";
    for ($i=$counter; $i<($datos_x_fila*($r+1)); $i++) {
        if($counter<count($datos)) {
            echo '<td style="border: 1px solid #666;">Caja#'.($counter+1).'<br>'.$datos[$counter].'</td>';
            $counter++;
        }
    }
    echo "</tr>";
}

echo "</table>";
    
answered by 06.06.2018 в 09:09