0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】TBを作成 ※n列で改行して余りはハイフン

Last updated at Posted at 2022-04-19

TBを作成 ※4列で改行して余りはハイフン

パターン1.1

<?php $data = ['フシギダネ','フシギソウ','フシギバナ','ヒトカゲ','リザード','リザードン','ゼニガメ','カメール','カメックス']; ?>
<table>
    <tr>
        <th colspan ="<?php echo $col = 4;?>">ポケモン</th>
    <tr><?php
        $int = 0;
        $wari = count($data) % $col;
        foreach($data as $list){ 
            if($int % $col === 0 && $int > 0) echo '</tr><tr>';
            echo '<td>',$list ?: '調査中','</td>';
            $int++;
        } 
        echo $wari !== 0 ? str_repeat('<td>-</td>',$col - $wari):'';?>
    </tr>
</table>

image.png

パターン1.2 ※残りはテーブル結合

※下記の場合は出力するTD数が決まっている前提なので、ハイフンは表示しない

<?php
$data = ['フシギダネ','フシギソウ','フシギバナ','ヒトカゲ','リザード']; ?>
<table>
    <tr>
        <th colspan ="<?php echo $col = 6;?>">ポケモン</th>
    <tr><?php
        $td_col = 2;
        $cnt = count($data);
        $wari = count($data) % 3;
        foreach($data as $td => $list){ 
            if($td % 3 === 0 && $td > 0) echo '</tr><tr>';

            if($wari === 2 && $cnt === 2){
                $td_col = 3;
            }
            echo '<td colspan=',$td_col,'>',$list,'</td>';
            $cnt--;
        }?>
    </tr>
</table>

image.png

<?php
$data = ['フシギダネ','フシギソウ','フシギバナ','ヒトカゲ','リザード']; ?>
<table>
	<tr>
		<th colspan ="<?php echo $col = 2;?>">ポケモン</th>
	<tr><?php
		$td_col = 1;
		$cnt = count($data);
		$wari = count($data) % 2;
		foreach($data as $td => $list){ 
			if($td % 2 === 0 && $td > 0) echo '</tr><tr>';

			if($wari === 1 && $cnt === 1){
				$td_col = 2;
			}
			echo '<td colspan=',$td_col,'>',$list,'</td>';
			$cnt--;
		}?>
	</tr>
</table>

image.png

パターン2

<?php $data = ['フシギダネ','フシギソウ','フシギバナ','ヒトカゲ','リザード','リザードン','ゼニガメ','カメール']; ?>
<table>
    <tr>
        <th rowspan ="<?php echo ceil(count($data)/$col = 4);?>">ポケモン</th><?php 
        $int = 0;
        $wari = count($data) % $col;
        foreach($data as $list){ 
            if($int % $col === 0 && $int > 0)echo '</tr><tr>'; 
            echo '<td>',$list['name'] ?: '調査中','</td>';
            $int++;
        }
        echo $wari !== 0 ? str_repeat('<td>-</td>',$col - ($wari % $col)):'';?>
    </tr>
</table>

image.png

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?