Sheldon
Sheldon

Reputation: 10077

How do I give group headings for my results in Codeigniter view?

I have list like this in my view:

<? foreach($services as $service): ?>
<tr>
  <td><?= $service->name; ?></td>
  <td><?= $service->format; ?></td>
  <td><?= $service->member; ?></td>
  <td><?= $service->non_member; ?></td>
</tr>
<? endforeach; ?>

But I'd like to spilt up the results into a couple of tables based on $service->grouping; so it would look look similar to:

<h2><?= $service->grouping; ?></h2>

<? foreach($services as $service): ?>
    <tr>
      <td><?= $service->name; ?></td>
      <td><?= $service->format; ?></td>
      <td><?= $service->member; ?></td>
      <td><?= $service->non_member; ?></td>
      <td><?= $service->grouping; ?></td>
    </tr>
    <? endforeach; ?>

<h2><?= $service->grouping; ?></h2>

<? foreach($services as $service): ?>
        <tr>
          <td><?= $service->name; ?></td>
          <td><?= $service->format; ?></td>
          <td><?= $service->member; ?></td>
          <td><?= $service->non_member; ?></td>
        </tr>
        <? endforeach; ?>

Services is equal to:

$this->data["services"]= $this->services_model->group_by("grouping")->get_all();

Is there a way to group the results and give a title to each grouping before looping through the next table?

Upvotes: 0

Views: 37

Answers (2)

Mateusz Odelga
Mateusz Odelga

Reputation: 354

You can also use array_filter with callback

E.g.:

<? foreach($services as array_filter($service,function($value) {return $value->grouping == "GROUP1"; }): ?>
<tr>
  <td><?= $service->name; ?></td>
  <td><?= $service->format; ?></td>
  <td><?= $service->member; ?></td>
  <td><?= $service->non_member; ?></td>
</tr>
<? endforeach; ?>

References

http://www.php.net/manual/en/function.array-filter.php

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227240

You can loop over $services and separate the values based on $service->grouping. Something like this:

<?php
$groupedServices = array();

foreach($services as $service){
    if(!isset($groupedServices[$service->grouping])){
        $groupedServices[$service->grouping] = array();
    }

    $groupedServices[$service->grouping][] = $service;
}

Then, when you print it in the view, just use 2 foreach loops.

<?php foreach($groupedServices as $grouping=>$services): ?>
    <tr>
        <td colspan="4"><?=$grouping?></td>
    </tr>
    <?php foreach($services as $service): ?>
        <tr>
          <td><?=$service->name?></td>
          <td><?=$service->format?></td>
          <td><?=$service->member?></td>
          <td><?=$service->non_member?></td>
        </tr>
    <?php endforeach; ?>
<?php endforeach; ?>

Upvotes: 1

Related Questions