HTML 表的 PHP 類別:奇怪的屬性分配
P粉384679266
P粉384679266 2023-09-06 00:38:07
0
1
361

在建立 HTML 表格的類別中,我有這個呈現表格的方法。除了某些條件下的 HTML 屬性分配之外,一切都正常運作(縮排、結束標籤、資料表示等)。當我設定單元格資料時,我會呼叫 setData() 來接收三個參數並像這樣使用它。注意我如何設定第三個參數(單元格屬性):

方法定義:

public function setData( array $data, array $row_attributes = [], array $cell_attributes = [] ): bool { // the code }

通話:

$table->setData( $pagination->resultset, [], // row attributes array( // cell attributes array(), // row 1 (index 0) array( // row2 (index 1) ["id"=>"R2C1id"], // row 2, cell 1 ["id"=>"R2C2id", "onclick"=>"R2C2_onclick();"], // row 2, cell 2 ), array( // row 3 [], [], ["id"=>"R3C3id", "selected"=>"selected"], // row 3, cell 3 [], [], [], [] ) ) );

在此範例中,表格有七個欄位。

在這裡您將看到 HTML 輸出。注意第二行和第三行的單元格屬性:

1
Consumidor Final
Consumidor Final
1
2
Prueba SRL
Tu Prueba
12345678901
1
3
Otra Prueba SA
Prueba 2
12345678902
1

這是我用來完成這一切的程式碼。我將向您展示單元格渲染的程式碼片段以及處理屬性的方法。

儲存格渲染:

// process cells $row_counter = 0; foreach ($this->data as $data) { // row $row_build = ""; $cell_counter = 0; foreach ($data as $cell_data) { // cell if ($cell_counter < $col_count) { $row_build .= $this->getHtmlDiv( $html_cell_class, $cell_data ?? "", $this->getHtmlAttributes("cell", $row_counter, $cell_counter), 3 ); } $cell_counter ; } // $cell_counter ; // complete empty cells to preserve row:hover on full row while ($cell_counter < $col_count) { $row_build .= $this->getHtmlDiv( $html_cell_class, "", $this->getHtmlAttributes("cell", $row_counter, $cell_counter), 3 ); $cell_counter ; } $body_build .= $this->getHtmlDiv( $html_row_class, $row_build, $this->getHtmlAttributes("row", $row_counter, 0), 2, true ); $row_counter ; }

屬性的方法:

private function getHtmlAttributes(string $section, int $row, int $column): array { if (count($this->html_attributes[$section]) > 0) { if (array_key_exists($row, $this->html_attributes[$section])) { if ($section === "cell") { if (array_key_exists($column, $this->html_attributes[$section][$row])) { return $this->html_attributes[$section][$row][$column]; } } return $this->html_attributes[$section][$row]; } } return []; }

怎麼了?謝謝。

P粉384679266
P粉384679266

全部回覆 (1)
P粉349222772

好吧,當我發布問題並選擇程式碼時,答案出現了。在方法getHtmlAttributes()中,缺少else條件。

private function getHtmlAttributes(string $section, int $row, int $column): array { if (count($this->html_attributes[$section]) > 0) { if (array_key_exists($row, $this->html_attributes[$section])) { if ($section === "cell") { if (array_key_exists($column, $this->html_attributes[$section][$row])) { return $this->html_attributes[$section][$row][$column]; } else { // <-- this return []; } } return $this->html_attributes[$section][$row]; } } return []; }
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!