2

重複の可能性:
ネストされたphp三項トラブル:三項出力!= 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戻り番号、フロートタイプ。

4

3 に答える 3

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'));
于 2012-12-29T12:42:35.720 に答える
0

コードを再度チェックする必要がある場合に将来それらを理解できるように、単純なif/elseステートメントで三項演算子を使用する方が適切です。したがって、この場合は、最初に投稿したコードを使用することをお勧めします。

于 2012-12-29T12:47:44.203 に答える
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;
  } 
}

ハードコーディングされていても問題ない場合は、longifステートメントを使用してください。あなたはそれを簡単にコメントすることができ、それは読み、コメントするのが簡単です:

// 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")
    )
  );
于 2012-12-29T12:50:44.050 に答える