【问题标题】:Result by year then month php array foreach结果按年然后按月php数组foreach
【发布时间】:2015-12-09 04:59:00
【问题描述】:

我被困在一个 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
  • 一月
  • 列表项

希望有人可以帮忙。谢谢

【问题讨论】:

  • 你能print_r($rows);吗?

标签: php mysql loops mysqli foreach


【解决方案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

【讨论】:

  • 谢谢你,但是当我回显年份和月份时,我只得到 ARRAY 而不是年份和月份 foreach($something as $year) { echo '&lt;b&gt;Year &amp;nbsp;'.$year. '&lt;/b&gt;&lt;br&gt;'; 有什么建议吗?
  • 嗯,是数组。您可以随时var_dumpprint_r。它有很大帮助。我已经编辑了一些答案。
  • 谢谢我今晚学到了一些东西$something[$year][$month][] = $row 是我无法解决的一点现在有意义.. 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 1970-01-01
相关资源
最近更新 更多