2012-07-26 46 views
0

我婉下面的代碼從這個PHP基本轉換如果然後其他

$diff = strtotime($row['start']) - strtotime($current); 
if ($diff < 7200) { 
    echo 'Starts soon'; 
} else if ($diff <= 0) { 
    echo 'Started'; 
} else { 
    echo 'Starts'; 
} 

這種轉換?

<?= ($current > $row['start']) ? 'Started' : 'Starts'; ?> 

如何以這種方式寫(如果可能的話)?

+0

據我所知,簡寫'如果else'不能適用於其他'if' – asprin 2012-07-26 12:09:03

+3

你原來的條件是假的「入門」將永遠不會被打印,因爲如果第二個是第一個條件將永遠是真實的,並執行。 – complex857 2012-07-26 12:12:22

+0

否則如果($ DIFF <= 0)塊將永遠不會被執行。 – FatalError 2012-07-26 12:13:50

回答

2

這不是很可讀的,所以我不會使用它,但在這裏你去:

echo ($diff < 7200) ? 'Starts soon': (($diff <= 0) ? 'Started': 'Starts'); 
0

這不是很漂亮,但你可以做這樣的:

<?php 
$diff = strtotime($row['start']) - strtotime($current); 
echo ($diff < 7200 ? 'Start soon' : ($diff <= 0 ? 'Started' : 'Starts')); 
?> 

或者

<?= ((strtotime($row['start']) - strtotime($current)) < 7200 ? 'Start soon' : ((strtotime($row['start']) - strtotime($current)) <= 0 ? 'Started' : 'Starts')); ?> 
0

否則,如果能當else部分,如果你添加新的應用。

<?= (($diff < 7200) ? "Starts soon" : (($diff <= 0) ? "Started" : "Starts")); ?> 
+1

這是不正確的。三元運算符在PHP左關聯的,你需要一個額外的對括號。 – phant0m 2012-07-26 12:12:30

0

沒有什麼錯與if elseif聲明覆蓋了幾行。它可以很容易閱讀,容易理解和容易地看到發生了什麼,如果你以後檢查你的代碼 - 或者更重要的是當其他人閱讀你的代碼。

記住,它始終是更容易編寫的代碼比它是閱讀的。

documents

<?php 
// on first glance, the following appears to output 'true' 
echo (true?'true':false?'t':'f'); 

// however, the actual output of the above is 't' 
// this is because ternary expressions are evaluated from left to right 

// the following is a more obvious version of the same code as above 
echo ((true ? 'true' : false) ? 't' : 'f'); 

// here, you can see that the first expression is evaluated to 'true', which 
// in turn evaluates to (bool)true, thus returning the true branch of the 
// second ternary expression. 
?> 

這真的不是太明智的,因爲它是難以閱讀和容易誤讀。