Chama
Chama

Reputation: 199

How to clean up this strange PHP code?

this script outputs the birthdays as headlines and the customer(s) below.

So the output is "grouped" by the date of birth.

echo "<div>";

foreach(pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty)) as $row)
    {
        if(!isset($birthday) or $birthday != $row['birthday'])
            {
                unset($drawline);
                echo "</div>";
                echo "<div class=title><h1>".$row['birthday']."</h1></div><div class=customer>";
            }

        if(isset($drawline)){echo "<hr>";}

        echo $row['customer']."<br>";

        $drawline = 1;

        $birthday = $row['birthday'];
    }

echo "</div>";

'birthday' is a DATE-field in the database.

Between the customers there's always a line (hr), but not after the last customer of a d.o.b.

Example output:

<div class=title><h1>1986-10-08</h1></div>
<div class=customer>
Don Foo<br>
<hr>
Joe Bar<br>
</div>

<div class=title><h1>1988-03-18</h1></div>
<div class=customer>
Jane Fonda<br>
<hr>
Elvis Burns<br>
</div>

Is it possible to remove the <div> and </div> outside the foreach()?

It produces always an empty <div></div>.

Upvotes: 0

Views: 70

Answers (1)

Nikolay Konovalov
Nikolay Konovalov

Reputation: 77

I've decided that it's too much hassle on the programmer's mind to see what's happening here, so here is much cleaner version of your code.

<?php
$people = pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty));
if (!empty($people)) {
// Find out people with the same birthday and group them.
$birthdays = [];
foreach ($people as $man) {
    $birthday = $man['birthday'];
        if (empty($birthdays[$birthday])) {
            $birthdays[$birthday] = [];
        }
        $birthdays[$birthday][] = $man['customer'];
    }
// Now let's output everything!
?>
<div>
<?php foreach ($birthdays as $birthday => $customers): ?>
    <div class=title><h1><?= $birthday ?></h1></div>
    <div class="customer">
        <?= implode('<br><hr>', $customers) ?>
    </div>
<?php endforeach;?>
</div>
<?php } // endif (!empty($people)) ?>

Main point of this solution - very simple to understand, uses somewhat templating (you could create one for this little snippet), easy to debug and modify. And yes, it does not output the empty <div></div> anymore!

Upvotes: 2

Related Questions