I have a desc array created from a scandir(). Here is a small example of the array:
[7] => 20151227NY [8] => 20151226NY [9] => 20151221NY [10] => 20151125CT [11] => 20140313NY [12] => 20140228NY [13] => 20140227NY [14] => 20140226NH [15] => 20140226CT [16] => 20140128NJ [17] => 20140123NY [18] => 20140122CT [19] => 20140121NJ [20] => 20140102NY [21] => 20131231NJ
These are all folders named using YearMonthDateState. I need a way to grab all the folders containing "NY", "CT", "NJ", "NH" and put them in separate arrays that sort in desc order(latest date first). That way I can get files I need in them according to the latest date(which is in the folder name). I tried this:
//GET WEEKLY FOLDER
$weekly_dir = "../email/weekly/";
$weekly_files = scandir($weekly_dir, $sorting_order = 1);
$weekly_index = $weekly_files[7];
$weekly_state = substr($weekly_index, 8,2);
$new_weekly = str_replace($weekly_state, $template->State, $weekly_index);
echo $new_weekly;
But unfortunately, not every new "weekly" is uploaded on the same date. So I cant just switch the state string ("NY" "NH" etc) at the end. Any ideas?
**UPDATE:**I have added/modified the code as suggested by Michael so my code now looks like this:
$weekly_dir = "../email/weekly/";
$weekly_file_array = scandir($weekly_dir, $sorting_order = 1);
$index = $weekly_file_array;
// Prepare result
$weeklies = array_fill_keys(array_map(function ($item) {
if (substr($item, -2) == 'NY'){
return substr($item, -2);
}
}, $index),$item);
// Split into state arrays
array_walk($index, function ($item) use (&$weeklies) {
$state = substr($item, -2);
$weeklies[$state][] = $item;
});
$weeklies_latest = array_combine(array_keys($weeklies), array_map(function ($item) {
sort($item);
return array_pop($item);
}, $weeklies));
Seems to work just fine, but I get these two errors at the top of page: "Warning: sort() expects parameter 1 to be array, null given" "Warning: array_pop() expects parameter 1 to be array, null given". I am calling the $weeklies_latest array like this:
<a href="/COMM/email/weekly/<? echo $weeklies_latest[$template->State] ?>/weekly.html" class="button-link button-link-blue">CURRENT ISSUE</a>