我试图让这个PHP表单元格根据条件写颜色,但我错过了导致语法错误的东西?
代码如下:
$table = '<table>
<tr>
<th> Qty </th>
<th> Length </th>
<th> Description </th>
<th> Color </th>
</tr>
<tr>
<td></td>
<td></td>
<td>'.$gauge. ' ' .$panel. '</td>'
if ($sscolor == "None")
{
'<td>' .$color. '</td>';
}
else
{
'<td>' .$sscolor. '</td>';
}
'</td>
</tr> ';
是。不能将if/else条件放在字符串中。你可以使用三元制。
$str = 'text'.($sscolor == 'None' ? $color : $sscolor).' more text'; // etc
否则,您需要在if之前结束字符串,然后使用.=
在向变量写入字符串后,不能在变量中放置IF条件我建议你这样做
if ($sscolor == "None")
{
$extra_string = '<td>' .$color. '</td>';
}
else
{
$extra_string = '<td>' .$sscolor. '</td>';
}
$table = '<table>
<tr>
<th> Qty </th>
<th> Length </th>
<th> Description </th>
<th> Color </th>
</tr>
<tr>
<td></td>
<td></td>
<td>'.$gauge. ' ' .$panel. '</td>' . $extra_string . '
</tr> ';
问题是您需要在if
语句之前用分号;
关闭字符串连接。如果你不这样做,那么你会得到一个语法错误:
<td>'.$gauge. ' ' .$panel. '</td>' <-- Semicolon here
if ($sscolor == "None") <-- Syntax error, unexpected if token
避免这种情况的一个好方法是使用heredoc字符串:
// Figure out the color before going into the string
if ($sscolor === 'None') {
$color = $sscolor;
}
// heredoc string, with string interpolation
$table = <<< HTML
<table>
<tr>
<th>Qty</th>
<th>Length</th>
<th>Description</th>
<th>Color</th>
</tr>
<tr>
<td>-</td>
<td>-</td>
<td>{$gauge} {$panel}</td>
<td>{$color}</td>
</tr>
</table>
HTML;
了解更多关于字符串的信息。
而且,即使是最好的PHP程序员也必须处理错误。这是学习PHP的一部分。因此,您应该养成在谷歌上搜索错误消息的习惯;它们很容易找到,你可以在帮助自己的同时学习。
您需要将if语句中的行连接起来。
<td>'.$gauge. ' ' .$panel. '</td>';
if ($sscolor == "None") {
$table .= '<td>' .$color. '</td>';
} else {
$table .= '<td>' .$sscolor. '</td>';
}
$table .= '</td>';