Search code examples
phparrayscodeignitermodel-view-controllerresultset

How to transfer 2d result set array from CodeIgniter model to the view layer?


I have a model who returns an array like this:

array(1) {
    [0]=> array(4) {
        ["report_title"]=> string(7) "Test #1"
        ["content"]=> string(24) "This is a test"
        ["author"]=> string(6) "Thomas"
        ["create_date"]=> string(10) "1304969836"
    }
}

And this is my controller:

$report_id = $this->uri->segment(3);
$report = $this->Report_model->getReport($report_id, $company_id);
if (!$report) {
    // TODO: fix this if the getReports returns FALSE;
} else {
    $data['report'] = $report;
}
$this->load->view('user/report_read', $data);

My problem is that I can't access the result set data in my view layer. I have tried different ways, but I can't get it to work.

My view:

echo $report['report_title']; // Error: Message: Undefined index: report_title
echo $report_title; // Error: Undefined variable: report_title

How can I solve the problem?


Solution

  • You are trying to access it correctly the first time ($report['report_title']). Your problem is that your $report is an array of reports. If this is not what you are after, review your model and adjust the return value. If it is, loop through $report with a foreach in your view to output a list of reports. Using your code above, something like this should work:

    <?php foreach ( $report as $r ): ?>
    Title: <?php echo $r['report_title']; ?> <br />
    Content: <?php echo $r['report_content']; ?> <br />
    <?php endforeach; ?>