Advertisement
cdsatrian

[php] menambah kolom otomatis sesuai jumlah data

Mar 26th, 2024
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.92 KB | None | 0 0
  1. <?php
  2. //-- jumlah data yang akan ditampilkan, random dari 3 sd 26
  3. $num_data=rand(3,26);
  4. //-- jumlah baris maksimum = 5
  5. $max_row=5;
  6. $data=array();
  7. for($no=1;$no<=$num_data;++$no){
  8.     $data[$no]="data ke-{$no}";
  9. }
  10. $row_col_data=array();
  11. $row=1;
  12. $col=1;
  13. foreach($data as $no=>$dt){
  14.     if(!isset($row_col_data[$row]))
  15.         $row_col_data[$row]=array();
  16.     $row_col_data[$row][$col]=$dt;
  17.     if($row % $max_row == 0) {
  18.         ++$col;
  19.         $row=1;
  20.     } else {
  21.         ++$row;
  22.     }
  23. }
  24. ?>
  25. Jumlah data : <?php echo $num_data;?><br>
  26. Jumlah baris : <?php echo $max_row;?><br>
  27. <table border="1">
  28. <tr>
  29.     <?php
  30.     $col=$row==1?--$col:$col;
  31.     for($ncol=1;$ncol<=$col;++$ncol){
  32.         echo "<th>kolom ke-{$ncol}</th>";
  33.     }
  34.     ?>
  35. </tr>
  36. <?php
  37. for($nrow=1;$nrow<=$max_row;++$nrow){
  38.     echo "<tr>";
  39.     for($ncol=1;$ncol<=$col;++$ncol){
  40.         echo "<td>".(isset($row_col_data[$nrow][$ncol])?$row_col_data[$nrow][$ncol]:'&nbsp;')."</td>";
  41.     }
  42.     echo "</tr>";
  43. }
  44. ?>
  45. </table>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement