Evelyn
Evelyn

Reputation: 656

Concatenate same array(number) from database

It's a bit hard to explain here but I'll try my best to include all related information. You can ask me if you don't understand.

enter image description here

Above is the data I got and I wish to combine the same number (e.g 2016) to be displayed as shown below.

enter image description here

This is my code.

<?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 } ?>

This is my database enter image description here enter image description here

May I know how to combine the year? I used "GROUP BY" but cannot, it hides the 2nd row of data. Or should I compare the value and combine it? But I have no idea how to do this. Please help, thank you.

Upvotes: 0

Views: 48

Answers (2)

msvairam
msvairam

Reputation: 872

Try this coding...

You are get result value and apply in your html content.

     <?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 } }
         } }   ?>

Upvotes: 1

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4749

Update your code like this:

$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 
} ?>

Upvotes: 0

Related Questions