如何在Codeigniter视图中为我的结果提供组标题?

时间:2014-06-17 15:52:24

标签: php html codeigniter

我的观点中有这样的列表:

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

但我想根据$ service-&gt;分组将结果分成几个表格;所以它看起来类似于:

<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; ?>

服务等于:

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

在循环浏览下一个表之前,有没有办法对结果进行分组并为每个分组提供标题?

2 个答案:

答案 0 :(得分:1)

您可以循环$services并根据$service->grouping分隔值。像这样:

<?php
$groupedServices = array();

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

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

然后,当您在视图中打印它时,只需使用2个foreach循环。

<?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; ?>

答案 1 :(得分:0)

您也可以将array_filter与回调

一起使用

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; ?>

参考

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