从数据库连接相同的数组(数字)

时间:2016-01-13 04:21:50

标签: php mysql database row concatenation

这里有点难以解释,但我会尽力包含所有相关信息。如果你不理解,你可以问我。

enter image description here

以上是我得到的数据,我希望将相同的数字(例如2016)组合在一起,如下所示。

enter image description here

这是我的代码。

<?php
    $years = mysql_query("SELECT DISTINCT YEAR(event_date) as years, DATE_FORMAT(event_date,'%b') as months from news WHERE status<>'deleted' and status<>'draft' ORDER BY years DESC");

    while($page=mysql_fetch_array($years))
    { ?>
        <div class="date">
            <div class="year"><a href="<?php echo $sys_domain; ?>/news/index.php?year=<?php echo $page['years'] ?>&month=<?php echo $page['months'] ?>"><?php echo $page['years']; ?></a></div>

            <div class="month"><a href="<?php echo $sys_domain; ?>/news/index.php?year=<?php echo $page['years'] ?>&month=<?php echo $page['months'] ?>"><?php echo $page['months']; ?></a></div> 
        </div>
<?php } ?>

这是我的数据库 enter image description here enter image description here

我可以知道如何结合这一年吗?我使用&#34; GROUP BY&#34;但不能,它隐藏第二行数据。或者我应该比较价值并结合它?但我不知道该怎么做。请帮忙,谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个编码...

您将获得结果值并应用于您的HTML内容。

     <?php
        $years = mysql_query("SELECT DISTINCT YEAR(event_date) as years, DATE_FORMAT(event_date,'%b') as months from news");

        $result = array();

        while($page=mysql_fetch_array($years))
        {

            $year = $page['years']; 
            $month = $page['months'];

            $result[$year][] = $page['months'];

        }   

        if(isset($result)) {

        foreach($result as $key=>$year_array) { ?>

           <div class="year"><a href="<?php echo $sys_domain; ?>/news/index.php?year=<?php echo $key; ?>&month=<?php echo $month; ?>"><?php echo $key; ?></a></div>
           <?php 
           if(isset($year_array) && count($year_array) != 0) { 
                foreach($year_array as $month) { ?>

                     <div class="month"><a href="<?php echo $sys_domain; ?>/news/index.php?year=<?php echo $key; ?>&month=<?php echo $month; ?>"><?php echo $month; ?></a></div> 

            <?php } }
         } }   ?>

答案 1 :(得分:0)

像这样更新你的代码:

$years = mysql_query("SELECT YEAR(event_date) as years, GROUP_CONCAT(DATE_FORMAT(event_date,'%b') SEPARATOR '<br />') as months from news GROUP BY YEAR(event_date)");
while($page=mysql_fetch_array($years))
{ ?>
    <div class="year"><?php echo $page['years']; ?></div>
    <div class="month"><?php echo $page['months']; ?></div>  <?php 
} ?>