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 关注
- 151 浏览
添加回答
举报