Search code examples
phpforeachcheckboxlist

Different markup based on foreach output


I've been trying to figure this out for a couple of days but no luck so far unfortunately. I want to sort appointments based on category/type and put them in seperate divs. For example:

My foreach loop generates an input checkbox for each available appointment of type 'normal' and 'special'.

Now I can get a list of ALL appointments with:

print $apptOutput;

This outputs a list of appointments that users can select by using checkboxes:

  • 30-08-16 11:05 Special
  • 31-08-16 09:55 Special
  • 31-08-16 20:05 Normal
  • 01-09-16 20:00 Normal
  • 02-09-16 20:05 Normal

What I'm trying to do is giving each category a different div so the output is seperated. For example, I want it to be this:

<div id="normal">
  <label for="normal">Normal</label>
    <?php print $apptOutput; ?>
</div>

And for Special:

<div id="special">
  <label for="special">Special</label>
     <?php print $apptOutput; ?>
 </div>

Solution

  • You can't easily solve the problem at the stage that you have $appOutput if it's already generated HTML. You need to solve it at the point that you're generating $appOutput, because then it's easier to identify which things are Special and which are Normal.

    Let's say you get this data from a database. At the point that you're traversing the result set from your database, you can place each item in a distinct array key based this criteria of Special and Normal, making it easier to generate the output of each type of item into its own div.

    $data = [
        "Special" => [],
        "Normal"  => [],
    ];
    // $resultSet being your database result set or however you get the data
    foreach($resulSet as $result) {
        if ($result["type"] == "Special") {
            $data["Normal"][] = $result;
        } elseif ($result["type"] == "Normal") {
            $data["Special"][] = $result;
        }
    }
    

    Now in your template you can more easily generate the result.

    <div id="normal">
        <?php foreach($data["Nomral"] as $item) { ?>
            <label for="normal"><?=$item['name']?></label>
            <input type="checkbox" ...>
        <?php } ?>
    </div>
    
    <div id="special">
        <?php foreach($data["Special"] as $item) { ?>
            <label for="normal"><?=$item['name']?></label>
            <input type="checkbox" ...>
        <?php } ?>
    </div>