我怎样才能使这个PHP <td>有条件的


How can I make this PHP <td> Conditional?

我试图让这个PHP表单元格根据条件写颜色,但我错过了导致语法错误的东西?

代码如下:

$table = '<table>
<tr>
 <th> Qty </th>
 <th> Length </th>
 <th> Description </th>
 <th> Color </th>
</tr>
<tr>
 <td></td>
 <td></td>
 <td>'.$gauge. ' &nbsp; ' .$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. ' &nbsp; ' .$panel.  '</td>' . $extra_string . '
</tr> ';

问题是您需要在if语句之前用分号;关闭字符串连接。如果你不这样做,那么你会得到一个语法错误:

<td>'.$gauge. ' &nbsp; ' .$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} &nbsp; {$panel}</td>
      <td>{$color}</td>
    </tr>
  </table>
HTML;

了解更多关于字符串的信息。

而且,即使是最好的PHP程序员也必须处理错误。这是学习PHP的一部分。因此,您应该养成在谷歌上搜索错误消息的习惯;它们很容易找到,你可以在帮助自己的同时学习。

您需要将if语句中的行连接起来。

<td>'.$gauge. ' &nbsp; ' .$panel.  '</td>';
 if ($sscolor == "None") {
    $table .= '<td>' .$color. '</td>';    
 } else {
     $table .= '<td>' .$sscolor. '</td>';
 }
$table .= '</td>';