Group dates in a foreach loop

前端 未结 3 697
日久生厌
日久生厌 2021-01-15 04:54

I want to add a new line in order to group dates within a foreach loop.

Example:

2015-11-05
2015-11-05

2015-11-07

2015-11-10
2015-11-1         


        
相关标签:
3条回答
  • 2021-01-15 05:30

    One way to do this is to save the previous value and compare it to the current one:

    $prev = NULL;
    foreach($rows AS $row) {
        $curr = $row['datetime_published'];
        echo "$curr<br>";
        if ($curr != $prev) {
            echo '<br>';
            $prev = $curr;
        }
    }
    
    0 讨论(0)
  • 2021-01-15 05:36
    $temp="":
    foreach($rows AS $row) {
            $my_date = $row['datetime_published'];
            echo $my_date.'<br>';
             if(strcmp($my_date,$temp)==0)
               echo '<br>';
            $temp = $my_date;
    
        }
    
    0 讨论(0)
  • 2021-01-15 05:46

    Both answers provided by Mureinik and Subin are good. But you also have the option to do the following

    1. Edit your query to something like this
    SELECT datetime_published,count(*) as count,`id_visitor`,`id_category`,`datetime_published`,`datetime_edited`,`data_content` FROM table group by `datetime_published` order by `datetime_published` desc
    
    1. Now you have an array with the dates and the count it should print these dates. Then you can print it with a 'for loop'
    for ($i = 1; $i <= $row['count']; $i++) {
    echo $row['datetime_published']." ".$row['data_content'] .'<br>';
    }
    echo "<br>";
    

    Complete Solution spoiler

    <?php
    
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    $con=mysqli_connect("dbhost","dbuser","dbpass","db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $sql = "SELECT datetime_published,count(*) as count FROM date group by `datetime_published` order by `datetime_published` desc";
    //print $sql;
    if ($result=mysqli_query($con,$sql))
      {
      // Fetch one and one row
      while ($row=mysqli_fetch_assoc($result))
        {
    
        $var = "select * from date where datetime_published = '".$row['datetime_published'] ."'";
        print $row['datetime_published']."<br>";
            if ($results=mysqli_query($con,$var))
            {
                // Fetch one and one row
                while ($rows=mysqli_fetch_assoc($results))
                {
                print $rows['data_subject']. " " . $rows['data_content'];
                echo "<br>";
                }
            }
        echo "<br>";
        }
    
    
    }
    echo "<br>";
    
      // Free result set
      mysqli_free_result($result);
    
    
    mysqli_close($con);
    ?>
    
    0 讨论(0)
提交回复
热议问题