0

我怎么能把这个 if 语句变成三元语句?

if ( !empty($vendor_address_row['address2'])){
    $address_obj['address2'] = $vendor_address_row['address2'];
    }else{
    $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>';    
    }

我试过了

$vendor_address_row['address2'] ? $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $address_obj['address2'] = '';

!empty($vendor_address_row['address2']) ? $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $address_obj['address2'] = '';

都不工作。除此之外,可能还有更短的方法可以做到这一点。非常感谢。

4

3 回答 3

1

这取决于是否$vendor_address_row['address2']总是定义。

如果是(并且版本 >= 5.3):

$address_obj['address2'] = $vendor_address_row['address2'] ?: '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>';

或(版本 < 5.3):

$address_obj['address2'] = $vendor_address_row['address2'] ? $vendor_address_row['address2'] : '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>';

它不是:

$address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>';

如果需要,您可以反转操作数以摆脱!empty()

于 2012-11-26T02:02:04.367 回答
0

this should be:

echo $address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : ('<tr><td colspan="1">'.$address_row['address2'].'</td></tr>');

or to save it to a variable:

$address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : ('<tr><td colspan="1">'.$address_row['address2'].'</td></tr>');
于 2012-11-26T01:58:45.990 回答
0

It should be

$address_obj['address2'] = empty($vendor_address_row['address2']) ? '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $vendor_address_row['address2'] ;
于 2012-11-26T02:00:27.380 回答