提供的代码中的语法错误是什么:

时间:2011-07-15 20:17:32

标签: php syntax

$pollPart .= '
<tr>
<td valign="top" nowrap="nowrap">'.$question['question'].'</td>
<td valign="top" height="10" width="100%" style="padding: 0px 10px;">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="top" width="'.$percentage.'%" '.if($percentage > 0){$pollPart .= 'style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"';}.'><img src="/includes/poll/images/dot.gif" width="1" height="19" /></td>
<td valign="top" width="'.$percentage2.'%"></td>
</tr>
</table>
</td>
<td valign="top">'.$responses['total'].'</td>
</tr>
';

我在下一行获得语法:

<td valign="top" width="'.$percentage.'%" '.if($percentage > 0){$pollPart .= 'style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"';}.'><img src="/includes/poll/images/dot.gif" width="1" height="19" /></td>

特别是这部分:

if($percentage > 0){$pollPart .= 'style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"';}

非常感谢您的任何意见,谢谢!

3 个答案:

答案 0 :(得分:4)

您不能在分配给变量的字符串中使用if条件。你可以尝试:

(($percentage > 0)?'style="background: url(\'/includes/poll/images/bar.jpg\')':'')

答案 1 :(得分:1)

你不能在串联串内进行if-blocks。如果你想做一个内联三元if / else,语法会有所不同。

而不是

... if($percentage > 0){$pollPart .= 'style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"';} ...

你可以像CONDITION ? TRUE-PART : FALSE-PART

那样构建它
... (($percentage > 0) ? 'style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"' : '') ...

我使用空字符串(''),因为不需要错误条件,但需要返回一些内容才能完成语句并与字符串的其余部分连接。

或者,你可以结束你的串联串,在它之后放置if块,然后再用$pollPart .=重新开始。

答案 2 :(得分:1)

$pollPart .= '
<tr>
<td valign="top" nowrap="nowrap">'.$question['question'].'</td>
<td valign="top" height="10" width="100%" style="padding: 0px 10px;">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="top" width="'.$percentage.'%"';

if($percentage > 0){
    $pollPart .= ' style="background: url(\'/includes/poll/images/bar.jpg\') repeat-x;"';
}

$pollPart .='><img src="/includes/poll/images/dot.gif" width="1" height="19" /></td>
<td valign="top" width="'.$percentage2.'%"></td>
</tr>
</table>
</td>
<td valign="top">'.$responses['total'].'</td>
</tr>';