我有一个包含三列的CSV文件: 玛丽,150203_15:29:12,150203_16:10:12 约翰,150203_15:29:17,待定 彼得,150203_15:29:35,150203_15:49:35 奥尔加,150203_15:30:43,以待 ... .. 。 玛丽,150204_15:42:14,以待 彼得,150204_20:42:14,以待
因为该文件上有许多条目,所以我想要做的是根据用户名查找最新条目并更改最后一个值(从挂起到日期())。 在上面的示例中,我想要更改第3列中从挂起到日期的最新Mary条目。 然后用当前的CSV文件替换更新的CSV文件。
关于如何处理的任何想法?
谢谢
I have a CSV file with three columns: Mary,150203_15:29:12,150203_16:10:12 John,150203_15:29:17,pending Peter,150203_15:29:35,150203_15:49:35 Olga,150203_15:30:43,pending ... .. . Mary,150204_15:42:14,pending Peter,150204_20:42:14,pending
Because there are many entries on that file all I want to do is find the latest entry according to the Username and change the last value (from pending to date()). In the example above lets say I want to change the latest Mary entry in the 3rd column from pending to date. Then replace the updated CSV file with the current one.
Any ideas on how to approach that?
Thank you
最满意答案
您可以将该文件作为一个巨大的字符串使用并进行字符串替换。
$data = file_get_contents('your_file.csv'); $data = str_replace('Joe,150203_16:21:43,pending','Joe,15203_16:21:43,15204_15:23:43',$data); file_put_contents('your_file.csv', $data);下面的评论引起了一个问题,即找出一个名字的最新日期。 这也很简单。 假设您已加载$ data,如上所述......
$matches = array(); // Just to point out that this is an array preg_match_all("/Joe,(.*),/", $data, $matches);现在,$ matches [1]包含Joe的所有日期。 你只想要那些待定的吗? 没问题...
preg_match_all("/Joe,(.*),pending/", $data, $matches);现在,$ matches [1]只包含待定日期。 哪个是最近的?
rsort($mathes[1]);现在,$ matches [1] [0]是最近的日期。 所以,你可以这样做:
$data = str_replace('Joe,'.$matches[1][0].',pending','Joe,'.$matches[1][0].',15204_15:23:43',$data);这是绝对最有效的方法吗? 不,难道难受吗? 不。您应该考虑使用正确的数据库,但可以使用csv文件。
You can work with the file as one huge string and do a string replacement.
$data = file_get_contents('your_file.csv'); $data = str_replace('Joe,150203_16:21:43,pending','Joe,15203_16:21:43,15204_15:23:43',$data); file_put_contents('your_file.csv', $data);The comments below raise a concern of finding out what the latest date is for a name. That is also rather simple to do. Assuming you've loaded $data in, as above...
$matches = array(); // Just to point out that this is an array preg_match_all("/Joe,(.*),/", $data, $matches);Now, $matches[1] contains all the dates for Joe. Did you ONLY want the ones that are pending? No problem...
preg_match_all("/Joe,(.*),pending/", $data, $matches);Now, $matches[1] only contains the pending dates. Which is the most recent?
rsort($mathes[1]);Now, $matches[1][0] is the most recent date. So, you can do:
$data = str_replace('Joe,'.$matches[1][0].',pending','Joe,'.$matches[1][0].',15204_15:23:43',$data);Is this the absolute most efficient way to do this? No. Is it impossibly hard? No. You should look into using a proper database, but it is possible to use csv files.
更多推荐
发布评论