开发者

Grouping dates in PHP

开发者 https://www.devze.com 2023-02-26 08:41 出处:网络
I have a table of dates and appointments in a MYSQL database. I\'d like to print the contents of this to a fi开发者_StackOverflowle, each date that has an appointment i\'d like to group them under i

I have a table of dates and appointments in a MYSQL database.

I'd like to print the contents of this to a fi开发者_StackOverflowle, each date that has an appointment i'd like to group them under it.

e.g

<h1>Appontments on 28/01/11<h1>
<p>10am Visit mum</p>
<p>12pm eat cake</p>

The format of my table is ID(int), date(DATE), Time(TIME), Description(varchar), Place (varchar)

Whats the best way to go about this, I was thinking of using one loop to find all the dates, then an other loop within that loop to find all the appointments for each date. Is there a more efficient way?

Thanks for your time and excuse my bad explanation of the problem.


Something like this is about as optimal as I know how to do it (assuming you have the space in memory, which obviously shouldn't be an issue here):

$query = "SELECT * FROM appointments GROUP BY `date`";
// Because of the algorithm used to sort dates below, you don't even really
// need the GROUP BY. But what the heck, right?

$result = mysqli_query($mysql, $query);

$appointments = array();

while ($row = mysqli_fetch_assoc($result))
{
    if (!isset($appointments[$row['date']]))
    {
        $appointments[$row['date']] = array();
    }

    $appointments[$row['date']] []= $row;
}

foreach ($appointments as $date => $items)
{
    echo "<h1>{$date}</h1>";

    echo "<ul>";

    foreach ($items as $item)
    {
        echo "<li>{$item['Dime']}: {$item['Description']} " . 
             "@ {$item['Place']}</li>";
    }

    echo "</ul>";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消