【问题标题】:Output every month in a year in foreach loop PHP在foreach循环PHP中一年中的每个月输出
【发布时间】:2015-12-09 13:03:40
【问题描述】:

我有一个在 foreach 循环中输出假期的 mysql 查询。例如。 2015 年 1 月 15 日 Steven 假期、3 月 12 日 jim 假期 2 月 20 日 jon 假期 2016 年 1 月 10 日假期等。我如何列出一年中的所有月份而不仅仅是假期的月份?

$monthx = array('January'=>null, 'Febuary'=>null, 'March'=>null, 'April'=>null, 'May'=>null, 
'June'=>null, 'July'=>null, 'August'=>null, 'September'=>null, 'October'=>null, 'November'=>null, 'December'=>null); 
while ($row = mysqli_fetch_assoc($result)) { 
    $year = $row['year'];
$month = $row['month'];
$years[$year][$month][] = $row;
//print_r($something);
}

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

我的想法是创建一个包含所有月份的数组,然后将该数组与包含来自 mysql 的所有数据的数组合并。我试过这个没有成功。任何帮助都会很棒。

【问题讨论】:

  • 您的代码对我来说看起来不错。运行时发生了什么? “没有成功”不是对问题的描述。请阅读minimal reproducible example
  • @Anders 不确定如何将 $monthx 与 $Month =row['month' 合并以输出一月二月三月等。代码仅在 MySQL 中运行良好,但不确定如何实现 array_merge 或 array_merge_recursive 我有重复的键,例如。一月,三月在mysql查询中。因为我是新手,甚至不确定这是解决这个问题的正确方法。

标签: php mysql arrays foreach


【解决方案1】:

要列出所有月份,您只需对所有月份运行foreach 循环。这种情况下不需要合并:

$monthx = array('January', 'Febuary', 'March', 'April', 'May', 
  'June', 'July', 'August', 'September', 'October', 'November', 'December'); 

while ($row = mysqli_fetch_assoc($result)) { 
  $year = $row['year'];
  $month = $row['month'];
  $years[$year][$month][] = $row;
  //print_r($something);
}

foreach($years as $year => $months)  {
  echo '<b>Year &nbsp;'.$year. '</b><br>';

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

【讨论】:

  • 谢谢你,当有时它让你面对时,我一直在深入研究......所以逻辑是 $monthx 是数组,然后如果月份作为记录,那么对于每个项目那个月在 MySQL 中获取项目并回显。只是让我在我的脑海里再次感谢
  • 一个快速的问题,如果该月没有项目,我如何回显未找到记录我是否对 isset 有一个 else 语句
  • 我已添加无记录文本,感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多