![](/img/trans.png)
[英]How to put switch case statement inside a foreach loop in php?
[英]Is it possible to put switch case inside while loop?
場景是我將從數據庫中提取一些數據並通過pdf輸出。 我使用FPDF
來實現它,而我需要從數據庫中獲取高度並根據顏色顯示它。
例如:
我的問題是我正在嘗試將switch case
插入while loop
以將高度放在要顯示其他數據的表上。 下圖顯示了要在其中實現彩色單元的位置 。 應該在“ SS Height”列中實現。
但這不起作用,並給了我這個錯誤。
這是我的代碼。
<?php
require('connection.php');
$sql="SELECT * FROM table ORDER BY ssh REGEXP '^[^A-Za-z0-9]' ASC, ssh DESC";
$records=mysql_query($sql);
$fetch = mysql_fetch_array($records);
require("library/fpdf.php");
$pdf = new PDF('p', 'mm', 'Legal');
$title = 'Storm Surge Warning';
$pdf->SetTitle($title);
$pdf->AliasNbPages('{pages}');
$pdf->SetAutoPageBreak(true,25);
$pdf->AddPage();
$pdf->SetBorders(array('LT', 'LT', 'LT', 'LT', 'TLR'));
$pdf->SetWidths(array(30, 27, 35, 51, 51));
$pdf->SetAligns(array('C', 'C', 'C', 'L', 'L'));
$pdf->SetFont('Arial', 'B', 10);
$pdf->Row(array("SS Height",
"Provinces",
"Low Lying Coastal Areas in the Municipalities of:",
"IMPACTS",
"ADVICE/Actions to Take"), 1);
$pdf->SetFont('Arial', '', 11);
while($row = mysql_fetch_array($records)){
$pdf->Row(array(
switch ($row['ssh']) {
case '2-3Meters' :
$pdf->SetFillColor(204, 153, 0);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
case '1-2Meters' :
$pdf->SetFillColor(255, 255, 0);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
case '<1Meter' :
$pdf->SetFillColor(51, 153, 255);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
default:
$pdf->Cell($row['ssh'], 1, 1, 'L', FALSE);
break;
}
$row['provi'],
$row['muni'],
$row['impact'],
$row['advice']), 1);
}
$pdf->SetBorders(array('T', 'T', 'T', 'T', 'T'));
$pdf->Row(array('','','','',''), 1, false, 1);
$pdf->OutPut();
?>
您的開關(TRUE)應該使用高度如下的代碼:
switch ($row['ssh'] ) {
case '2-3Meters' : {
$pdf->SetFillColor(204, 153, 0);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
}
case '1-2Meters' : {
$pdf->SetFillColor(255, 255, 0);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
}
case '<1Meter' : {
$pdf->SetFillColor(51, 153, 255);
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
break;
}
default:
...
無論如何,在不了解FPDF API如何工作的情況下,似乎它只是保留了全局狀態。
因此,首先調用switch +着色(數組映射會更簡單),然后添加-> Cell,最后添加-> Row,如下所示:
while($row = mysql_fetch_array($records)){
switch ($row['ssh']) {
case '2-3Meters' :
$pdf->SetFillColor(204, 153, 0);
…
}
$pdf->Cell($row['ssh'], 1, 1, 'L', TRUE);
$pdf->Row(array(1,2,3,4,1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.