2010-01-24 86 views
1

過濾器,我有以下CSVPHP讀取CSV和日期

Date,Event,Description 
24/01/2010,Football,Football practice for all Years. 
24/01/2010,Cricket,Cricket Practice for all Years. 
25/01/2010,Piano Lessons,Paino lessons for Year 10. 

Date, Event and Description是我想要篩選頭。

我收到今天的日期,然後我想讀取CSV並輸出符合今天日期的事件。我也想獲得明天的事件。

回答

1

最快(但不是最佳)的方法是使用fgetcsv,然後迭代表格,選出今天的日期。

我可能會重新考慮數據的格式(使其成爲數據庫),除非有其他應用程序依賴於它。

0

有很多方法可以讀取CSV文件;您還可以逐行閱讀並使用拆分功能將每個字段作爲數組中的一個元素進行分隔。

如果搜索速度和複雜性不是問題,您可以進行線性迭代並檢查日期。您可能需要使用strtotime將日期轉換爲unix時間戳以進行比較。

如果搜索速度是很重要的,然後再轉換的日期戳,有一個關聯數組,其關鍵是時間戳(本質上是一個哈希表)

爲了讓明天的日期,檢查出date function documentation in the PHP manual

3

如上所述,您確實想使用fgetcsv()。這裏是你會如何做(未經測試):

<?php 
if (($handle = fopen("test.csv", "r")) !== FALSE) { 
    $today = strtotime("today"); 
    $tomorrow = strtotime("tomorrow"); 
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     if (strtotime($data[0]) == $today || strtotime($data[0]) == $tomorrow)) { 
      echo 'Category: ' . $data[1] . "<br>\n"; 
      echo 'Event: ' . $data[0] . "<br><br>\n\n"; 
     }   
    } 
    fclose($handle); 
} 
?> 
0

單程

$today=date('d/m/Y'); 
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); 
$tmr = date("d/m/Y", $tomorrow)."\n"; 
$handle = fopen("file", "r"); 
fgets($handle,2048); 
while (($data = fgetcsv($handle, 2048, ",")) !== FALSE) { 
    $date=explode("/",$data[0]); 
    if ($today == $data[0] || $tmr == $data[0]){ 
     $j = implode(",", $data); 
     print $j."\n"; 
    } 
} 
fclose($handle); 
0

作爲替代fgetcsv和迭代,你也可以使用正則表達式來獲得相應的線路,例如對於

Date,Event,Description 
24/01/2010,Football,Football practice for all Years. 
24/01/2010,Cricket,Cricket Practice for all Years. 
25/01/2010,Piano Lessons,Paino lessons for Year 10. 
26/01/2010,Piano Lessons II. 

使用

date_default_timezone_set('Europe/Berlin');  
$pattern = sprintf('#%s.*|%s.*#', date('d/m/Y'), 
            date('d/m/Y', strtotime("+1 day"))); 
$file = file_get_contents('filename.csv'); 
preg_match_all($pattern, $file, $matches); 
var_dump($matches); 

和接收

array(1) { 
    [0]=> 
    array(3) { 
    [0]=> string(53) "24/01/2010,Football,Football practice for all Years." 
    [1]=> string(51) "24/01/2010,Cricket,Cricket Practice for all Years." 
    [2]=> string(52) "25/01/2010,Piano Lessons,Paino lessons for Year 10." 
    } 
} 

有沒有這個基準測試,雖然。根據CSV文件的大小,由於file_get_contents將整個文件加載到變量中,這可能會佔用大量內存。


另一個替代SplFileObject

$today = date('d/m/Y'); 
$tomorrow = date('d/m/Y', strtotime("+1 day")); 
$file = new SplFileObject("csvfile.csv"); 
$file->setFlags(SplFileObject::READ_CSV); 
foreach ($file as $row) { 
    list($date, $event, $description) = $row; 
    if($date === $today || $date === $tomorrow) { 
     echo "Come visit us at $date for $description"; 
    } 
} 
0

你可以花很多時間試圖遍歷CSV文件中的每一行,或者可以嘗試類似的東西:

$command = sprintf("grep '%s' -Er %s", date('d/m/Y'), $this->db); 
$result = `$command`; 

這個例子真的有用,它非常快!