结果按年然后一个月的php数组foreach

时间:2015-09-12 20:59:40

标签: php mysql loops mysqli foreach

我被困在一个php foreach循环中。我想做的是按年度,然后在那一年的每个月得到结果。

 $sql = "SELECT DATE_FORMAT(datestart, '%M') as month,
    MONTH(datestart) AS m,
    YEAR(datestart) AS year,
    holiday.Id,
    employeeId,
    datestart,
    dateEnd,
    DATE_FORMAT(holiday.dateEnd,'%D %M, %Y') AS end,
    DATE_FORMAT(holiday.datestart,'%D %M, %Y') AS startit,
    DATE_FORMAT(holiday.datestart,'%d-%m-%Y') AS st,
    DATE_FORMAT(holiday.datestart,'%d-%m-%Y') AS en,
    CONCAT(employees.empFirst,' ',employees.empLast) AS employee,
    DATE_FORMAT(holiday.datestart,'%d-%m-%Y %H:%i') AS start
    From holiday
    LEFT JOIN employees ON holiday.employeeId = employees.empId
    ORDER BY year asc, m, datestart
";

$result = $mysqli->query($sql);
$res = $mysqli->query($sql);
$months = array();
while ($row = mysqli_fetch_assoc($result)) { 
    $months[$row['month']][] = $row;
}

foreach($months as $months => $month) {
    echo '<b>Month &nbsp;'.$months. '</b><br>';
    foreach($month as $item){ 
        echo $item['employee']. '&nbsp;-&nbsp;'
            .$item['startit'].'&nbsp;-&nbsp;'.$item['end'].'<br/>';
    }
}

我得到的结果是月份然后项目例如。

  • 一月 项目详情
  • 三月 项目详情
  • 十月 项目详情

我所追求的是:

  • 2015
  • 一月
  • 项目详情
  • 三月
  • 项目详情
  • 十月
  • 项目详情
  • 2016
  • 一月
  • 列表项

我希望有人可以帮忙。谢谢

1 个答案:

答案 0 :(得分:1)

我希望这部分代码可以帮助你。

# some code

$year = $row['year']; # Important part.
$month = $row['month'];
$something[$year][$month][] = $row

# some code

foreach($something as $year => $months) { # Important part.
    # some code
    foreach($months as $month => $items) {
        # some code
        foreach($items as $item) {

# some code