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


Checking Date Part of a CSV Date-and-Time Cell

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

当前代码:

$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:06pm'

使用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);

似乎在工作

可以存储日期的时间戳&将时间而不是'15/01/2013 12:06pm'或其他内容放入文件中,以便您可以检索时间戳并按照自己的意愿格式化日期。

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

您也可以使用SplFileObject设置为CSV模式,然后根据您的条件(单元格索引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);