在php if语句中为元素添加背景色


Adding background color to element within php if-statement

我有以下代码,我想在其中添加一个元素到我的if语句,但我不确定如何处理这一点。我要做的是添加一个背景色的其他部分。在这个:

else {
        $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}

如果$status不为0,我想为goal-box-right类设置背景色

我是否可以像这样通过php操作CSS ?

foreach ($rows as $row) {
            $status = $row['status'];
            if ($status == 0) {
                $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
            }
            else {
                $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
            }
            $goal_date = $row['date'];
            $fixed_goal_date = fixDate($goal_date);
            $html = "";
            $html .= '<div class="goal-box" id="comment-'.$row['id'].'">';
            $html .= '<div class="goal-box-left">'; //added
            $html .= '<div class="goal-post-status">'.$status_img. '</div>';
            $html .= '</div>'; //added
            $html .= '<div class="goal-box-right">'; //added
            $html .= '<div class="goal-post-title">'.$row['title']. '</div>';
            $html .= '<div class="goal-post-date">'.$fixed_goal_date. '</div>';
            $html .= '<div class="goal-post-description">'.$row['description']. '</div>';
            $html .= '</div>'; //added
            $html .= '</div>';

分离逻辑-根据状态添加CSS类,然后在样式表中设置颜色。

$class = $status != 0 ? 'status-nonzero' : '';
$html .= '<div class="goal-box-right ' . $class . '">';
CSS:

.goal-box-right.status-nonzero { background-color: #foo }

的优点是保持样式逻辑在它所属的CSS中,远离生成HTML的代码。

那么问题是什么呢:

$style = '';
if ($status == 0) {
    $style = ' style="your-style:here"';
    $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
}
else {
    $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}
// ...
$html .= '<div class="goal-box-right"' . $style . '>'; //added