2015-04-30 24 views
3

我一直在試圖列出當我去上學的時間,當我沒有。如何區分日期列表中的天數? PHP

我在這裏循環的日子。另一個陣列包含我沒有去上學的日子。

<?php 
$fecha1 = "2015-03-10"; 
$fecha2 = date("Y-m-d",strtotime($fecha1."+ 10 days")); 
$fecha3 = array("2015-03-11","2015-03-14","2015-03-17"); 
$j=1; 

for($i=$fecha1;$i<$fecha2;$i = date("Y-m-d", strtotime($i ."+ 1 days"))){ 
    for ($n=0; $n <count($fecha3) ; $n++) { 
     if($i==$fecha3[$n]){ 
      $obs="not there"; 

     }else{ 
      $obs="there";  
     } 
    } 
    echo "Day ".$j." ".$i."---".$obs."<br />"; 
    $j++; 
} 
?> 

和輸出

Day 1 2015-03-10---there 
Day 2 2015-03-11---there 
Day 3 2015-03-12---there 
Day 4 2015-03-13---there 
Day 5 2015-03-14---there 
Day 6 2015-03-15---there 
Day 7 2015-03-16---there 
Day 8 2015-03-17---not there 
Day 9 2015-03-18---there 
Day 10 2015-03-19---there 

我不明白爲什麼它不說「不存在」第2天2015-03-11 和第5天2015-03-14,有人幫助我,請我一直是這樣的小時。

+1

由於在所有'$ fecha3'項目你'for'循環迭代,你真的比較每次約會反對'2015 - 03-17'(數組中的最後一項)。使用@Ghost答案。 –

回答

3

您應該添加break一旦針頭發現:

if($i==$fecha3[$n]){ 
     $obs="not there"; 
     break; // this is important 
    }else{ 
     $obs="there"; 
    } 

另一種選擇是也in_array()用於搜索:

if(in_array($i, $fecha3)){ 
    $obs="not there"; 
}else{ 
    $obs="there"; 
} 
+0

謝謝你,它終於工作我瘋了, –

+0

@RildoGomez是啊,即使已經找到針,你正在迭代'$ fecha3'中的每個元素,你應該停止在那個點上。很高興這有助於 – Ghost

1

這是因爲2015-03-112015-03-14都在$fecha3的前兩個值數組,並且在第二個循環中被覆蓋。

在這種情況下,我會建議使用in_array()而不是爲循環第二:

$fecha1 = '2015-03-10'; 
$fecha2 = 10; 
$fecha3 = array('2015-03-11', '2015-03-14', '2015-03-17'); 

for ($i = 0; $i < $fecha2; $i++) { 
    $date = date('Y-m-d', strtotime($fecha1 . ' + ' . $i . ' days')); 
    $obs = in_array($date, $fecha3) ? 'not there' : 'there'; 
    echo 'Day ' . ($i + 1) . ' ' . $date . '---' . $obs . '<br />'; 
} 
+0

謝謝你的解釋,我正要問:) –

相關問題