使用php中的三元运算符根据sql中的事件状态来回显不同的状态


Using the ternary operator in php to echo different statuses based on an event status in sql

如果状态为1,则表示"活动保险事件",如果状态为2,则表示为"已完成保险事件"。

if(!empty($ins_event))
            {
            echo "<tr><td>&nbsp;<img src='/check-icon.gif'> <a href='". matry::here(array('event_id'=>$ins_event['id'])) . "'>" . ( $ins_event['status'] == 2 ? "Completed Insurance Event": "Active Insurance Event") . "</a></td></tr>"; 
            }
else 
        {
        echo "<tr><td>" . cbox_return() . "<a href='". matry::here_to('new', array('tfilt'=>'IN', 'pfilt'=>$patient->code)) . "' style='color: #000; color:$rx_image_color'>**Ins Event Not Created**</td></tr>";
        }

我这里有一个颜色变量:

<?php
$rx_event_colors = $rx_ev_status = '#009933';
?>

如何使用此变量获取2的状态并更改字体颜色。

我应该分解脚本并使用if{}else{}语句吗?


更新代码:

echo "<tr><td>&nbsp;<img src='/check-icon.gif'> <a href='". matry::here(array('event_id'=>$ins_event['id'])) . "'" . ( $ins_event['status'] == 2 ? ' style="color: ' . $rx_ev_status . '">Completed Insurance Event' : '>Active Insurance Event') . "</a></td></tr>"; 

您基本上会执行相同类型的三元运算:

($ins_event['status'] == 2 ? ' style="color: ' . $rx_ev_status . '"' : '')

这就是你的意思吗?你的问题不是那么清楚。。

if(!empty($ins_event))
            {
            echo "<tr><td>&nbsp;<img src='/check-icon.gif'> <a ".($ins_event['status'] == 2 ? 'style="color:'.$rx_ev_status.';"': '')." href='". matry::here(array('event_id'=>$ins_event['id'])) . "'>" . ( $ins_event['status'] == 2 ? "Completed Insurance Event": "Active Insurance Event") . "</a></td></tr>"; 
            }

这是一个编辑,为了清晰起见,将回声分解到不同的线上。。。

echo '<tr><td>&nbsp;<img src="/check-icon.gif">';
echo '<a '.($ins_event['status'] == 2 ? 'style="color:'.$rx_ev_status.';"': '')." ";
echo ' href="'. matry::here(array('event_id'=>$ins_event['id'])) . '">'; 
echo ($ins_event['status'] == 2 ? 'Completed Insurance Event': 'Active Insurance Event');
echo '</a></td></tr>'; 

是的,出于性能和代码维护的原因,逻辑操作应该尽可能少地进行。在单个if { … } else { … }块内设置文本状态和颜色变量。将状态和颜色存储到变量后,可以极大地简化echo语句。

echo "<tr><td>&nbsp;<img src='/check-icon.gif'> <a href='". matry::here(array('event_id'=>$ins_event['id'])) . "'>$status</a></td></tr>";

我还考虑将matry::here(…)的输出存储在一个变量中,以便更容易地读取代码。