如果日期已过,则从CSV中删除行

时间:2015-10-06 16:11:32

标签: php

我打开一个双列CSV,其中一列中的状态和另一列中的m / d / y格式的交付日期。我想删除日期早于最近对应日期的重复状态条目。

例如,如果CSV包含:

CA,1/5/16
CA,4/8/15
CA,3/2/15
OR,3/4/15
OK,3/4/14

......我只想存储:

CA,1/5/16
OR,3/4/15
OK,3/4/14

然后,我想将此新数组中的交付日期与当前日期进行比较,并仅显示过去具有日期的状态(仅限OR和OK)。为了提供背景信息,向州提供的交付有不同的部分,我只想列出完全交付货物的状态。

我坚持比较和删除日期部分,但我想其余部分。到目前为止,我有:

<?php

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $row=0;
    $csv_delivered = array();

    while (($line_of_text = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $date=$line_of_text[1];

        if(\DateTime::createFromFormat('m/d/y',$date) < new \DateTime()){
        //date is in the past
            $csv_delivered[] = $line_of_text;
        }
    }
    fclose($handle); 

    foreach ($csv_delivered as $delivered) {
        $states_delivered.= $delivered[0].","; //state
    } 
}

?>

    <p>Delivered: <?php echo $states_delivered; ?></p>

1 个答案:

答案 0 :(得分:2)

如果我找对你,

<?php

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $row=0;
    $csv_delivered = array();
    $state_date = array();     // holds date of last occurence
    $now = new \DateTime();

    while (($line_of_text = fgetcsv($handle, 1000, ",")) !== FALSE) {
        // ignore data that are in the future
        if ($state_date_min[$state]>$now) continue;

        // prepare
        $date=$line_of_text[1];
        $state=$line_of_text[0];
        $date = \DateTime::createFromFormat('m/d/y',$date);

        // store if not existing or overwrite if this one is newer
        if (!isset($state_date[$state]) || $date>$state_date[$state]) {
            $csv_delivered[$state] = $line_of_text;
            $state_date[$state] = $date;
        }

    }
    fclose($handle); 

    foreach ($csv_delivered as $state => $delivered) {
        $states_delivered.= $delivered[0].","; //state
    } 
}

?>

    <p>Delivered: <?php echo $states_delivered; ?></p>

记住每个州和商店的日期(如果不存在)或覆盖(如果不存在)。请忽略将来的所有数据。