检查CSV日期和时间单元格的日期部分

时间:2013-01-16 13:57:22

标签: php datetime csv

我目前正在使用php打开csv文件,检查包含特定内容的单元格并使用if-else获取特定信息。但是,我需要检查一个单元格是否包含某些信息的部分。

e.g。

当前代码:

$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
    $line_of_text = fgetcsv($error_handle, 1024);
    if($line_of_text[0] !== "")
        {
            $countErrors++;
        }
}
fclose($error_handle);

我想要的代码:

$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
    $line_of_text = fgetcsv($error_handle, 1024);
    if($line_of_text[4] == "$date *")
        {
            $countErrors++;
        }
}
fclose($error_handle);

'*'表示每行文本的时间不同,因此不能使用但是属于同一单元格的一部分。如何选择具有相同日期但不同时间的单元格?

仅供参考,日期格式通常为'15 / 01/2013 12:06 pm'

4 个答案:

答案 0 :(得分:1)

使用strpos功能:

if(strpos($line_of_text[4], "$date ") ===0) { found }

想想我已经明白了:

我正在使用以下内容:

        while (!feof($error_handle) )
        {
            $line_of_text = fgetcsv($error_handle, 1024);
            if(strpos($line_of_text[4], $date) !== false)
                {
                    $countErrors++;
                }
        }
    fclose($error_handle);

似乎正在运作

答案 1 :(得分:0)

您可以存储日期和时间戳的时间戳。时间而不是'15 / 01/2013 12:06 pm'或文件中的某些内容,以便您可以检索时间戳并根据需要设置日期格式。

答案 2 :(得分:0)

    while (!feof($error_handle) )
        {
            $line_of_text = fgetcsv($error_handle, 1024);
            if(strpos($line_of_text[4], $date) !== false)
                {
                    $countErrors++;
                }
        }
    fclose($error_handle);

答案 3 :(得分:0)

您还可以使用SplFileObject将其设置为CSV模式,然后filtering the rows based on your condition(单元格索引4,您的$date字符串比较)和计数(请参阅iterator_count) :

$rows     = new SplFileObject($reportUrl);
$rows->setFlags($rows::READ_CSV);
$filtered = new CallbackFilterIterator($rows, function ($current) use ($date) {
    return strpos($current[4], "$date ") === 0;
});
$countErrors = iterator_count($filtered);
相关问题