2 回答

TA貢獻1852條經驗 獲得超7個贊
通過使用一系列嵌套的foreachwithkey => value迭代器,你可以獲得你想要的輸出;關鍵是在到達循環底部之前不要輸出日期部分:
foreach ($post_search as $year => $months) {
? ? foreach ($months as $month => $days) {
? ? ? ? foreach ($days as $day => $files) {
? ? ? ? ? ? foreach ($files as $file) {
? ? ? ? ? ? ? ? echo "File $file:\nYear: $year\nMonth: $month\nDay: $day\n";
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
輸出(對于您的樣本數據):
File default.md:
Year: 2019
Month: 5
Day: 12
File default.md:
Year: 2019
Month: 12
Day: 22
File default.md:
Year: 2020
Month: 5
Day: 19

TA貢獻1852條經驗 獲得超1個贊
使用函數來處理令人困惑的嵌套方面應該會有很大幫助。我的例子絕不是一個可靠的解決方案。就個人而言,我可能會將這些函數放在一個類中并使其面向對象......但這絕對不是適合所有情況的正確解決方案。
您必須對此進行調整,但希望這個概念對您有所幫助。
function handleYear($year,$arrOfMonths){
echo $year;
foreach ($arrOfMonths as $month=>$arrOfDays){
handleMonth($month,$arrOfDays);
}
}
function handleMonth($month,$arrOfDays){
echo $month;
foreach ($arrOfDays as $dayOfMonth=>$listOfFiles){
handleDay($dayOfMonth,$listOfFiles);
}
}
//to get started
foreach ($data as $year=>$arrOfMonths){
echo $year;
handleYear($year, $arrOfMonths);
}
您還可以修改子函數以接受父參數。喜歡handleMonth也可以在年里度過,然后handleYear就過去了$year。
編輯:
看到你想要的輸出后......我建議將年份和月份傳遞給函數handleDay。然后handleDay可能是這樣的:
function handleDay($day,$arrOfFiles,$year,$month) use (&$files){
foreach ($arrOfFiles as $index=>$fileName){
$file = ['year'=>$year,'month'=>$month,'day'=>$day];
$files[] = $file;
}
}
然后你需要$files = []在函數外聲明,handleDay如果我沒記錯的話。
但這樣一來,您就擁有了一組可以非常輕松地處理的文件。
就個人而言,我可能會努力工作一段時間以提出一個更清潔的解決方案(不喜歡use這種情況下的聲明,我什至可能沒有正確使用它)。如果它在一個類中,那么您可以使用$this->files而不是use (&$files).
- 2 回答
- 0 關注
- 174 瀏覽
添加回答
舉報