Search code examples
phparrayscodeignitermodel-view-controller

Get 2d array from model, then pass from controller to view in CodeIgniter


I need to pass an array from my model (array is filled with info while reading a text file) to a controller and then finally to a view.

My model:

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

Controller:

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');   
}

And in view, I use this:

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

And I am getting error that notes variable is undefined in my view.


Solution

  • In your controller:

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

    EDIT:

    In your view:

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

    In your model:

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