Re: [請益] 合併儲存格

看板PHP作者 (寶貝豬)時間16年前 (2010/01/20 19:23), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串2/3 (看更多)
只要資料結構定義好, 再利用html的rowspan的特性, 即可做到. 以下程式碼可以正常運作. 可依需求自行修改. <?php //原始資料結構定義如下: 從資料庫撈出來的rows, 要先轉成這種形式. //撈資料過程從略. $data = array( '980001'=>array( 'class'=>'一年1班', 'stud_id'=>'980001', 'name'=>'王小明', 'clubs'=>array('扯鈴社','熱舞社') ), '980005'=>array( 'class'=>'一年1班', 'stud_id'=>'980005', 'name'=>'李大同', 'clubs'=>array('扯鈴社') ), '980006'=>array( 'class'=>'一年1班', 'stud_id'=>'980006', 'name'=>'張小芬', 'clubs'=>array('POP社') ), '980008'=>array( 'class'=>'一年1班', 'stud_id'=>'980008', 'name'=>'林中山', 'clubs'=>array() ) ); //轉成html格式後直接輸出(這裏不考慮套表或是對特殊字元轉碼的工序) echo tran2html($data); //轉成html table的形式 function tran2html($data){ $stream=''; $stream.=" <table border='1'> <tr> <td>班級</td> <td>姓名</td> <td>學號</td> <td>報名社團</td> </tr> "; foreach($data as $key => $entry): //根據學生加入社團的數量來決定列數: 若學生未加入社團, 則算一列 $rowspan=count($entry['clubs']); if($rowspan ==0) $rowspan=1; $stream.=sprintf(" <tr> <td rowspan='%d'>%s</td> <td rowspan='%d'>%s</td> <td rowspan='%d'>%s</td> ", $rowspan,$entry['class'], $rowspan,$entry['name'], $rowspan,$key ); //學生沒有參加任何社團的格式: if( empty($entry['clubs']) ): $stream.=sprintf(" <td rowspan='%d'>-</td></tr>", $rowspan ); //學生有加入至少一個社團的格式: else: //補上這行: 因為第一個社團跟後續的社團的所屬列的html不太一樣. $stream.=sprintf(" <td>%s</td></tr> ", array_shift($entry['clubs']) ); foreach($entry['clubs'] as $club): $stream.=sprintf(" <tr><td>%s</td></tr> ", $club ); endforeach; endif; endforeach; $stream.="</table>\n"; return $stream; } ?> ※ 引述《singlet (嗯)》之銘言: : 請問以下情況的迴圈該怎麼寫比較好呢?(不知道如何將rowspan放到前面去) : ┌────┬───┬───┬────┐ : │班級 │姓名 │學號 │報名社團│【原始的表格】 : ├────┼───┼───┼────┤ : │一年1班 │王小明│980001│扯鈴社 │ : ├────┼───┼───┼────┤ : │一年1班 │王小明│980001│熱舞社 │ : ├────┼───┼───┼────┤ : │一年1班 │李大同│980005│扯鈴社 │ : ├────┼───┼───┼────┤ : │一年1班 │張小芬│980006│POP社 │ : └────┴───┴───┴────┘ : ┌────┬───┬───┬────┐ : │班級 │姓名 │學號 │報名社團│←【期望的輸出結果】 : ├────┼───┼───┼────┤ : │ │ │ │扯鈴社 │ : │一年1班 │王小明│980001├────┤ : │ │ │ │熱舞社 │ : ├────┼───┼───┼────┤ : │一年1班 │李大同│980005│扯鈴社 │ : ├────┼───┼───┼────┤ : │一年1班 │張小芬│980006│POP社 │ : └────┴───┴───┴────┘ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 58.115.151.184 ※ 編輯: bobju 來自: 58.115.151.184 (01/20 19:25)

01/21 09:43, , 1F
修訂'社團所屬列'的html.
01/21 09:43, 1F
※ 編輯: bobju 來自: 58.115.151.184 (01/21 09:44)
文章代碼(AID): #1BLkVFFJ (PHP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):
文章代碼(AID): #1BLkVFFJ (PHP)