HTML 테이블 클래스

Table 클래스는 배열이나 데이터베이스 결과 집합에서 HTML 테이블을 자동 생성할 수 있는 메서드를 제공합니다.

테이블 클래스 사용

클래스 초기화

Table 클래스는 서비스로 제공되지 않으며 “일반적으로” 인스턴스화되어야 합니다. 예를 들면 다음과 같습니다.

<?php

$table = new \CodeIgniter\View\Table();

다음은 다차원 배열에서 테이블을 만드는 방법을 보여주는 예입니다. 첫 번째 배열 인덱스는 테이블 제목이 됩니다(또는 아래 함수 참조에 설명된 setHeading() 메서드를 사용하여 고유한 제목을 설정할 수 있습니다).

<?php

$table = new \CodeIgniter\View\Table();

$data = [
    ['Name', 'Color', 'Size'],
    ['Fred', 'Blue', 'Small'],
    ['Mary', 'Red', 'Large'],
    ['John', 'Green', 'Medium'],
];

echo $table->generate($data);

다음은 데이터베이스 쿼리 결과에서 생성된 테이블의 예입니다. 테이블 클래스는 테이블 이름을 기반으로 제목을 자동으로 생성합니다. 또는 아래 클래스 참조에 설명된 setHeading() 메서드를 사용하여 제목을 직접 설정할 수도 있습니다.

<?php

$table = new \CodeIgniter\View\Table();

$query = $db->query('SELECT * FROM my_table');

echo $table->generate($query);

다음은 개별 매개변수를 사용하여 테이블을 생성하는 방법을 보여주는 예입니다.

<?php

$table = new \CodeIgniter\View\Table();

$table->setHeading('Name', 'Color', 'Size');

$table->addRow('Fred', 'Blue', 'Small');
$table->addRow('Mary', 'Red', 'Large');
$table->addRow('John', 'Green', 'Medium');

echo $table->generate();

다음은 개별 매개변수 대신 배열이 사용된다는 점을 제외하면 동일한 예입니다.

<?php

$table = new \CodeIgniter\View\Table();

$table->setHeading(['Name', 'Color', 'Size']);

$table->addRow(['Fred', 'Blue', 'Small']);
$table->addRow(['Mary', 'Red', 'Large']);
$table->addRow(['John', 'Green', 'Medium']);

echo $table->generate();

테이블 모양 바꾸기

테이블 클래스를 사용하면 레이아웃 디자인을 지정할 수 있는 테이블 템플릿을 설정할 수 있습니다. 템플릿 프로토타입은 다음과 같습니다.

<?php

$template = [
    'table_open' => '<table border="0" cellpadding="4" cellspacing="0">',

    'thead_open'  => '<thead>',
    'thead_close' => '</thead>',

    'heading_row_start'  => '<tr>',
    'heading_row_end'    => '</tr>',
    'heading_cell_start' => '<th>',
    'heading_cell_end'   => '</th>',

    'tfoot_open'  => '<tfoot>',
    'tfoot_close' => '</tfoot>',

    'footing_row_start'  => '<tr>',
    'footing_row_end'    => '</tr>',
    'footing_cell_start' => '<td>',
    'footing_cell_end'   => '</td>',

    'tbody_open'  => '<tbody>',
    'tbody_close' => '</tbody>',

    'row_start'  => '<tr>',
    'row_end'    => '</tr>',
    'cell_start' => '<td>',
    'cell_end'   => '</td>',

    'row_alt_start'  => '<tr>',
    'row_alt_end'    => '</tr>',
    'cell_alt_start' => '<td>',
    'cell_alt_end'   => '</td>',

    'table_close' => '</table>',
];

$table->setTemplate($template);

참고

템플릿에는 두 세트의 “행” 블록이 있다는 것을 알 수 있습니다. 이를 통해 행 데이터의 각 반복에 따라 대체되는 행 색상이나 디자인 요소를 생성할 수 있습니다.

완전한 템플릿을 제출할 필요는 없습니다. 레이아웃의 일부만 변경해야 하는 경우 해당 요소를 제출하기만 하면 됩니다. 이 예에서는 테이블 열기 태그만 변경됩니다.

<?php

$template = [
    'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">',
];

$table->setTemplate($template);

템플릿 설정 배열을 테이블 생성자에 전달하여 이에 대한 기본값을 설정할 수도 있습니다.

<?php

$customSettings = [
    'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">',
];

$table = new \CodeIgniter\View\Table($customSettings);

제목과 행 동기화

Added in version 4.4.0.

setSyncRowsWithHeading(true) 메서드를 사용하면 연관 배열이 매개변수로 사용된 경우 각 데이터 값이 setHeading()에 정의된 것과 동일한 열에 배치됩니다. 이는 순서가 마음에 들지 않거나 API가 너무 많은 데이터를 반환하는 경우 REST API를 통해 로드된 데이터를 처리할 때 특히 유용합니다.

데이터 행에 제목에 없는 키가 포함되어 있으면 해당 값이 필터링됩니다. 반대로, 데이터 행의 제목에 키가 나열되어 있지 않으면 그 자리에 빈 셀이 배치됩니다.

<?php

$table = new \CodeIgniter\View\Table();

$table->setHeading(['name' => 'Name', 'color' => 'Color', 'size' => 'Size'])
    ->setSyncRowsWithHeading(true)
    ->addRow(['color' => 'Blue', 'name' => 'Fred', 'size' => 'Small'])
    ->addRow(['size' => 'Large', 'age' => '24', 'name' => 'Mary'])
    ->addRow(['color' => 'Green']);

echo $table->generate();
?>

<!-- Generates a table with this prototype: -->
<table border="0" cellpadding="4" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Color</th>
            <th>Size</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Fred</td>
            <td>Blue</td>
            <td>Small</td>
        </tr>
        <tr>
            <td>Mary</td>
            <td></td>
            <td>Large</td>
        </tr>
        <tr>
            <td></td>
            <td>Green</td>
            <td></td>
        </tr>
    </tbody>
</table>

중요

열 재배치가 발생하는 addRow([...])을 통해 행을 추가하기 전에 setSyncRowsWithHeading(true)setHeading([...])을 호출해야 합니다.

generate()에 대한 입력으로 배열을 사용하면 동일한 결과가 생성됩니다.

<?php

$data = [
    [
        'color' => 'Blue',
        'name'  => 'Fred',
        'size'  => 'Small',
    ],
    [
        'size' => 'Large',
        'age'  => '24',
        'name' => 'Mary',
    ],
    [
        'color' => 'Green',
    ],
];

$table = new \CodeIgniter\View\Table();

$table->setHeading(['name' => 'Name', 'color' => 'Color', 'size' => 'Size'])
    ->setSyncRowsWithHeading(true);

echo $table->generate($data);

수업 참고자료

class CodeIgniter\View\Table
$function = null

모든 셀 데이터에 적용할 기본 PHP 함수 또는 유효한 함수 배열 개체를 지정할 수 있습니다.

<?php

$table = new \CodeIgniter\View\Table();

$table->setHeading('Name', 'Color', 'Size');
$table->addRow('Fred', '<strong>Blue</strong>', 'Small');

$table->function = 'htmlspecialchars';
echo $table->generate();

위의 예에서 모든 셀 데이터는 PHP의 htmlspecialchars() 함수를 통해 실행되어 in::이 됩니다.

<td>Fred</td><td>&lt;strong&gt;Blue&lt;/strong&gt;</td><td>Small</td>
generate([$tableData = null])
매개변수:
  • $tableData (mixed) – 테이블 행을 채울 데이터

반환:

HTML 테이블

반환 형식:

string

생성된 테이블이 포함된 문자열을 반환합니다. 배열 또는 데이터베이스 결과 개체일 수 있는 선택적 매개 변수를 허용합니다.

setCaption($caption)
매개변수:
  • $caption (string) – 표 캡션

반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

테이블에 캡션을 추가할 수 있습니다.

<?php

$table->setCaption('Colors');
setHeading([$args = [][, ...]])
매개변수:
  • $args (mixed) – 테이블 열 제목을 포함하는 배열 또는 여러 문자열

반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

테이블 제목을 설정할 수 있습니다. 배열 또는 개별 매개변수를 제출할 수 있습니다.

<?php

$table->setHeading('Name', 'Color', 'Size'); // or

$table->setHeading(['Name', 'Color', 'Size']);
setFooting([$args = [][, ...]])
매개변수:
  • $args (mixed) – 테이블 바닥글 값을 포함하는 배열 또는 여러 문자열

반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

테이블 기초를 설정할 수 있습니다. 배열 또는 개별 매개변수를 제출할 수 있습니다.

<?php

$table->setFooting('Subtotal', $subtotal, $notes); // or

$table->setFooting(['Subtotal', $subtotal, $notes]);
addRow([$args = [][, ...]])
매개변수:
  • $args (mixed) – 행 값을 포함하는 배열 또는 여러 문자열

반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

테이블에 행을 추가할 수 있습니다. 배열 또는 개별 매개변수를 제출할 수 있습니다.

<?php

$table->addRow('Blue', 'Red', 'Green'); // or

$table->addRow(['Blue', 'Red', 'Green']);

개별 셀의 태그 속성을 설정하려면 해당 셀에 대한 연관 배열을 사용할 수 있습니다. 연관 키 data는 셀의 데이터를 정의합니다. 다른 모든 key => val 쌍은 태그에 key=’val’ 속성으로 추가됩니다.

<?php

$cell = ['data' => 'Blue', 'class' => 'highlight', 'colspan' => 2];
$table->addRow($cell, 'Red', 'Green');

?>

<!-- Generates: -->
<td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td>
makeColumns([$array = [][, $columnLimit = 0]])
매개변수:
  • $array (array) – 여러 행의 데이터를 포함하는 배열

  • $columnLimit (int) – 테이블의 열 수

반환:

HTML 테이블 열의 배열

반환 형식:

array

이 방법은 1차원 배열을 입력으로 사용하고 원하는 열 수와 동일한 깊이를 가진 다차원 배열을 만듭니다. 이를 통해 많은 요소가 포함된 단일 배열을 고정된 열 개수가 있는 테이블에 표시할 수 있습니다. 다음 예를 고려하십시오.

<?php

$list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'];

$newList = $table->makeColumns($list, 3);

$table->generate($newList);

?>

<!-- Generates a table with this prototype: -->
<table border="0" cellpadding="4" cellspacing="0">
    <tr>
        <td>one</td>
        <td>two</td>
        <td>three</td>
    </tr>
    <tr>
        <td>four</td>
        <td>five</td>
        <td>six</td>
    </tr>
    <tr>
        <td>seven</td>
        <td>eight</td>
        <td>nine</td>
    </tr>
    <tr>
        <td>ten</td>
        <td>eleven</td>
        <td>twelve</td>
    </tr>
</table>
setTemplate($template)
매개변수:
  • $template (array) – 템플릿 값을 포함하는 연관 배열

반환:

성공하면 참, 실패하면 거짓

반환 형식:

bool

템플릿을 설정할 수 있습니다. 전체 또는 부분 템플릿을 제출할 수 있습니다.

<?php

$template = [
    'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">',
];

$table->setTemplate($template);
setEmpty($value)
매개변수:
  • $value (mixed) – 빈 셀에 넣을 값

반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

비어 있는 테이블 셀에 사용할 기본값을 설정할 수 있습니다. 예를 들어, 잘림 방지 공백을 설정할 수 있습니다.

<?php

$table->setEmpty('&nbsp;');
clear()
반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

테이블 머리글, 행 데이터 및 캡션을 지울 수 있습니다. 서로 다른 데이터가 포함된 여러 테이블을 표시해야 하는 경우 각 테이블이 생성된 후 이 메서드를 호출하여 이전 테이블 정보를 지워야 합니다.

<?php

$table = new \CodeIgniter\View\Table();

$table->setCaption('Preferences')
    ->setHeading('Name', 'Color', 'Size')
    ->addRow('Fred', 'Blue', 'Small')
    ->addRow('Mary', 'Red', 'Large')
    ->addRow('John', 'Green', 'Medium');

echo $table->generate();

$table->clear();

$table->setCaption('Shipping')
    ->setHeading('Name', 'Day', 'Delivery')
    ->addRow('Fred', 'Wednesday', 'Express')
    ->addRow('Mary', 'Monday', 'Air')
    ->addRow('John', 'Saturday', 'Overnight');

echo $table->generate();
setSyncRowsWithHeading(bool $orderByKey)
반환:

테이블 인스턴스(메서드 체이닝)

반환 형식:

Table

각 행 데이터 키를 제목 키별로 정렬할 수 있습니다. 이를 통해 올바른 열에 배치되는 데이터를 더 효과적으로 제어할 수 있습니다. 첫 번째 addRow() 메서드를 호출하기 전에 이 값을 설정해야 합니다.