0

我有 2 个班级 - 具有多对多关系的学生和小组。在学生页面上,我想显示他的所有详细信息并列出他所属的所有组,用逗号分隔。这是我的学生控制器:

class Students extends Controller {

  function  __construct() {
      parent::__construct();
  }

  function index() {
      $this->get_all_students();
  }

  function get_all_students() {
      $s = new Student();
      $data['students'] = $s->select('id, name, email')->get();

      $this->load->view('students', $data);
  }

  function view($id) {
      $s = new Student();
      $s->get_by_id($id);
      $s->groups->get();

      $data['student'] = $s;

      $this->load->view('student_view', $data);
  }
}

我可以在 student_view 中获取学生的详细信息:

Name: <?php echo $student->name; ?>
E-mail: <?php echo $student->email; ?>
Groups: 
<?php foreach ($student->groups as $group) : ?>
  <?php echo anchor("/groups/$group->id", $group->name) ?>
<?php endforeach; ?>

那么,如何列出以逗号分隔的组?我尝试将组名添加到控制器中的数组中,然后仅<?php echo implode(', ', $groups); ?>在视图中。但是这样我就不能使用组 ID 建立链接。

4

2 回答 2

0
<?php echo anchor("/groups/$group->id", $group->name) ?> 

应该变成(见行尾的逗号)

<?php echo anchor("/groups/$group->id", $group->name) ?> ,

或将用户组显示为列表:

<?php foreach ($student->groups as $group) : ?>
  <?php echo anchor("/groups/$group->id", $group->name) ?>
<?php endforeach; ?>

应该成为

<ul>
<?php foreach ($student->groups as $group) : ?>
  <li><?php echo anchor("/groups/$group->id", $group->name) ?></li>
<?php endforeach; ?>
</ul>
于 2010-11-22T14:27:09.967 回答
0
<?php
  $first = true;
  foreach ($student->groups as $group) :
    if (! $first) echo ', ';
    echo anchor("/groups/$group->id", $group->name);
    $first = false;
  endforeach;
?>
于 2010-11-23T13:00:57.710 回答