三元运算符 PHP 中出现意外的右括号

Unexpected close parenthesis in ternary operator PHP

我有一个三元运算符,它会回显 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 />';
}

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

然而,在这种情况下,您的问题是因为您的父三元语句存在语法错误。他们没有定义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 />';
}

您在 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 />';