2012-08-13 100 views
0

简单,但对于我来说,作为一个初学者,一个问题。我需要从我的模型(数组充满信息的同时读取一个文本文件)传递一个数组到控制器,最后到一个视图。 我的模型:从模型获取数组,然后传递给查看

function show_notes(){ 
    $file = "notes.txt"; 

    foreach(file($file) as $entry) 
    { 
      list($user, $content) = array_map('trim', explode(':', $entry)); 
      $notes = array (
       'user'=> '$user', 
       'content'=> '$content' 
      ); 
    } 
    return $notes; 
} 

控制器:

function members_area() 
{ 
    $this->load->model('Note_model'); 
    $notes[] = $this->Note_model->show_notes(); 

    $this->load->view('includes/header'); 
    $this->load->view('members_area', $notes); 
    $this->load->view('includes/footer'); 
} 

,并鉴于我用这个:

 foreach ($notes as $item) 
    { 
    echo "<h1>$user</h>"; 
    echo "<p>$content</p>"; 
      } 

而且我得到错误笔记变量在我看来是不确定的。

我想我只是不明白数组是如何工作的。我试图阅读这个,我已经尝试了一些类似的例子,但仍然无法得到它。

回答

0

在你的控制器:

$data['notes'] = $this->Note_model->show_notes(); 
... 
$this->load->view('members_area', $data); 

编辑:

在你看来:

<?php foreach ($notes as $item):?> 
    <h1><?php echo $item['user']; ?></h1> 
    <p><?php echo $item['content'] ?></p> 
<?php endforeach; ?> 

在你的模型:

$notes = array(); 
foreach(file($file) as $entry) 
{ 
     list($user, $content) = array_map('trim', explode(':', $entry)); 
     array_push($notes, array('user' => $user, 'content' => $content)); 
} 
return $notes; 
+0

以及它看起来像这样的工作,但现在我得到了一个未定义的内容错误。它输出我的“用户”,但只有第一个重复 – tarja 2012-08-13 17:26:31

+0

@tarja我编辑了我的答案。 – 2012-08-13 17:29:54

+0

我已经按照你的建议做了,但我得到的错误:'array_push()期望参数1是数组,null给出' – tarja 2012-08-13 17:36:09

0

替换此

$notes[] = $this->Note_model->show_notes(); 

与此

$notes['notes'] = $this->Note_model->show_notes(); 
相关问题