2011-11-17 60 views
3

我最近使用CodeIgniter和PHP工作。我正在尝试做一个简单的任务来显示多级菜单。假设我有一个学生和状态表。我想显示哪些学生处于哪种状态(高中,初中等)。但我发现了这个错误:CodeIgniter的多级列表

A PHP Error was encountered 

Severity: Notice 

Message: Trying to get property of non-object 

Filename: views/sview.php 

Line Number: 31 

在第31行,我有

<?php echo $status->statusname;?> 

控制器:

// .... 
$data['status'] = $this->status_model->get_students(); 
$this->load->view('sview', $data); 

型号:

function get_students(){ 

    $s = $this->db->get('status'); 

    foreach ($s->result() as $status){ 

     $students = $this->db->get_where('student', array('status_id'=>$status->id)); 
     $status->students = students->result(); 
    } 

    return $s; 
} 

观点:

<?php foreach($s as $status):?> 
    <h4><?php echo $status->statusname;?></h4> 
    <?php foreach($status->student as $student):?> 
     <?php echo $student->studentname; ?> 
    <?php endforeach;?> 
<?php endforeach;?> 
+0

你的数据表是什么样子 – Rooster

+1

与你的错误信息无关,但是你的模型有一个语法错误,它看起来像:'$ status-> students = students-> result();'应该是'$ status- > students = $ students-> result();'(missing $) –

+1

我不知道codeignigter,但你的模型函数get_students看起来很可疑。你正在返回$ s; – Lylo

回答

0

你不是在get_students()在循环修改$s所以它只是从状态表中返回的所有记录的原始查询。您的循环中的$students变量也缺少'$'。

试试这个模型:

function get_students() 
{ 
    $s = $this->db->get('status'); 

    $statuses = array(); 

    foreach ($s->result() as $status) 
    { 
     $students = $this->db->get_where('student', array('status_id'=>$status->id)); 
     $status->students = $students->result(); 

     $statuses[] = $status; 
    } 

    return $statuses; 
} 

将在$statuses数组中返回修改后的$status变量,那么你就可以在你的意见对其进行访问。

0

您的控制器正在将$data['status']设置为它的所有不同状态。试试在你看来改变的情况如下:

<?php foreach($status as $s):?> 
    <h4><?php echo $s->statusname;?></h4> 
    <?php foreach($s->student as $student):?> 
     <?php echo $student->studentname; ?> 
    <?php endforeach;?> 
<?php endforeach;?>