简体   繁体   中英

PHP - Find latest file based on filename pattern

I have a bunch of gamers data. The data is stored as json with filename pattern as gamerid_date_time_seed.json . Eg below:

8841-2018-05-03-09-56-14-2118-data.json
8841-2018-05-03-10-50-22-1568-data.json
8841-2018-05-04-04-36-51-6081-data.json
8841-2018-05-04-06-56-50-1100-data.json

In the first filename for example, 2018-05-03-09-56-14 is the year-month-date-hour-min-sec format. 8841 is the gamer id and the last 4 digits, 2118 in this case is a seed value that can be ignored.

How can I parse this so that I get only the latest data file of a gamer? (In this case 8841-2018-05-04-06-56-50-1100-data.json) The issue is that sometimes a gamer might have multiple files but for same day.

I am not very good with regular expressions and stuff so I would really appreciate some help here.

You can use the glob function to get an array of files, and reverse sort to get the newest file as the first item in your array.

$gamerid = 8441;
$files = glob("filepath/".$gamerid."-*.json");
rsort($files);
$newestFile = $files[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM