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
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;
}
}
$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;
}
Both answers provided by Mureinik and Subin are good. But you also have the option to do the following
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
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);
?>