PHP中的比较运算符“IF”

时间:2012-12-29 12:36:42

标签: php if-statement

  

可能重复:
  nested php ternary trouble: ternary output != if - else

为什么这样做:

if($db->f('item_bonus') > 0)
    $bonus = $db->f('item_bonus').' (i)';
elseif($db->f('manufacturer_bonus') > 0)
    $bonus = $db->f('manufacturer_bonus').' (m)';
elseif($db->f('category_bonus') > 0)
    $bonus = $db->f('category_bonus'). ' (c)';

但是,这不起作用:

$bonus = $db->f('item_bonus') > 0 ? $db->f('item_bonus').' (i)' : $db->f('manufacturer_bonus') > 0 ? $db->f('manufacturer_bonus').' (m)' : $db->f('category_bonus') > 0 ? $db->f('category_bonus'). ' (c)' : '0';

我做错了什么? $db->f返回号码,浮点类型。

3 个答案:

答案 0 :(得分:1)

尝试分组:

$bonus = $db->f('item_bonus') > 0 ? $db->f('item_bonus').' (i)' : ($db->f('manufacturer_bonus') > 0 ? $db->f('manufacturer_bonus').' (m)' : ($db->f('category_bonus') > 0 ? $db->f('category_bonus'). ' (c)' : '0'));

答案 1 :(得分:0)

最好使用简单的if / else语句使用三元运算符,以便在将来再次检查代码时可以理解它们。所以在这种情况下,最好让你发布的第一段代码。

答案 2 :(得分:0)

如果你的理由是取消硬编码的if语句,你可以将功能和数据分开......

// Important stuff
// Change the order of bonus importance using this array
$bonus_precedence = array("item", "manufacturer", "category");
// Change the symbol for each item with this associative array
$bonus_markers = array(
  "item" => "i",
  "manufacturer" => "m",
  "category" => "c"
);

// Magic beyond here
foreach($bonus_precedence as $bonus_type) {
  // Get the next bonus type
  $bonus = $db->f("{$bonus_type}_bonus");
  // Was there a bonus
  if($bonus > 0) {
    // Output the bonus in full and break the loop
    $bonus_marker = $bonus_markers[$bonus_type];
    $bonus .= " ($bonus_marker)";
    break;
  } 
}

如果硬编码并不重要,请坚持使用long if语句。您可以轻松地对其进行评论,并且易于阅读和评论:

// Only one bonus type is allowed
// Item bonuses are the most important if there is
// an item bonus we ignore all other bonuses
if($db->f("item_bonus") > 0) {
  $bonus = "{$db->f("item_bonus")} (i)";

// Manufacturer bonuses are the next most important
} elseif($db->f("manufacturer_bonus") > 0) {
  $bonus = "{$db->f("manufacturer_bonus")} (m)";

// Category bonus is the fallback if there are no 
// other bonuses
} elseif($db->f("category_bonus") > 0) {
  $bonus = "{$db->f("category_bonus")} (c)";
}

否则至少试着让它易于理解:

// Only one bonus type is allowed
$bonus = 

  // Item bonuses are the most important if there is
  // an item bonus we ignore all other bonuses
  ($db->f("item_bonus") > 0 ? "{$db->f("item_bonus")} (i)" : 

    // Manufacturer bonuses are the next most important
    ($db->f("manufacturer_bonus") > 0 ? "{$db->f("manufacturer_bonus")} (m)" : 

      // Category bonus is the fallback if there are no 
      // other bonuses
      ($db->f("category_bonus") > 0 ? "{$db->f("category_bonus")} (c)" : "0")
    )
  );