php中如何分离和修改字符串的内容?

我读了一个 csv 文件,如下所示:


  391;WETSUITS;07/07/2020 12:47:36;0021000001463;

  392;WETSUITS;07/07/2020 12:47:49;0021000007845;

             ....

我用这种格式检索一个日期:


echo $data[2] = 07/07/2020 12:47:36

我想要两个变量:


$date = 07-07-2020 or 2020-07-07

$time = 1247

我尝试使用 str_replace 作为第一部分,但收到“注意:未定义偏移:2”作为错误消息,我该如何更改它?


 <?php


$csv = 'C:/wamp64/www/BI/BI1_20200707_1520_28044.csv';



if (($handle = fopen("$csv", "r")) !== FALSE) {

    while (($data = fgetcsv($handle, 9000000, ";")) !== FALSE){


            // echo $data[2]; //07/07/2020 12:47:36


        $new = str_replace('/', '_', $data[2]);

        echo $date = substr($new,0,20)."\n";;

 

    }

}


?>


ABOUTYOU
浏览 109回答 1
1回答

慕桂英3389331

此通知可能是由于文件末尾有空行而出现的。因此,只需检查$data数组是否为空即可。while (($data = fgetcsv($handle, 9000000, ";")) !== false) {&nbsp; &nbsp; &nbsp; &nbsp; // empty line will be transformed to [null]&nbsp; &nbsp; &nbsp; &nbsp; if (empty(array_filter($data))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; // other operations}建议:更好的是使用 DateTime 进行日期操作。日期格式参考: https: //www.php.net/manual/en/function.date$date = \DateTime::createFromFormat('d/m/Y H:i:s', $data[2]);if ($date === false) {&nbsp; &nbsp; // handle date parse error}$date1 = $date->format('Y-m-d'); // 2020-07-07$date2 = $date->format('Hi'); // 1247
打开App,查看更多内容
随时随地看视频慕课网APP