【问题标题】:Unexpected close parenthesis in ternary operator PHP三元运算符 PHP 中出现意外的右括号
【发布时间】:2016-12-21 11:08:14
【问题描述】:

我有一个三元运算符,它将回显 HTML 标记的样式。我已尝试删除或添加括号,但仍然出现错误。

foreach( $result as $row ) {
    $us = $row['username'];
    echo '<div id="msg_guest" style="'.($us != 'Admin' ? ($us != 'inTELLigence' ? 'float: right; background-color: #51b8c1':'float: left;')).'"><div id="usr" style="'.($us != 'Admin' ? ($us != 'inTELLigence'? 'background-color: #67d5de':'background-color: #e6898a')).'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';
}

【问题讨论】:

  • 这是一个示例,说明如何将逻辑分解为单独的行和部分将帮助您发现问题。用三元组编写一大行代码非常难以阅读。

标签: php ternary-operator


【解决方案1】:

对于left;')) 附近的第一条语句,您还没有完全关闭条件,您实际上需要left;') : '')

替换

echo '<div id="msg_guest" style="'.($us != 'Admin' ? ($us != 'inTELLigence' ? 'float: right; background-color: #51b8c1':'float: left;')).'"><div id="usr" style="'.($us != 'Admin' ? ($us != 'inTELLigence'? 'background-color: #67d5de':'background-color: #e6898a')).'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';

echo '<div id="msg_guest" style="'.( $us != "Admin" ? ($us != "inTELLigence" ? "float: right; background-color: #51b8c1":"float: left;") : '' ).'"><div id="usr" style="'.( $us != "Admin" ? ($us != "inTELLigence" ? "background-color: #67d5de":"background-color: #e6898a") : '').'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';

【讨论】:

  • 哦,我明白了。对于父语句,我没有 else/false 语句。谢谢!
  • @user5567987 是的。如果您觉得我的回答有帮助,请在我的回答上打勾:)
【解决方案2】:

您应该避免嵌套三元运算符,因为它很快就会变得非常混乱。

但是,在这种情况下,您的问题是因为父三元语句存在语法错误。他们没有定义 else。

例如你需要结束它:

$trueBoolean ? 'true condition' : 'false condition';

试试这样的。

foreach( $result as $row ) {
    $us = $row['username'];

    $html = '';
    if ($us != 'Admin') {
        $html = $us != 'inTELLigence' ? 'float: right; background-color: #51b8c1' : 'float: left;';
    }

    $html2 = '';
    if ($us != 'Admin') {
        $html2 = $us != 'inTELLigence' ? 'background-color: #67d5de' : 'background-color: #e6898a';
    }

    echo '<div id="msg_guest" style="'. $html .'"><div id="usr" style="'. $html2 .'"><div id="user">'.$row['username']. '</div><div id="time">'.$row['time_now'].'</div></div><p id="msg"> '.$row['message'].'</p></div><br />';
}

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多