Codeigniter在视图中使用foreach [英] Codeigniter using foreach in view

查看:121
本文介绍了Codeigniter在视图中使用foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Apache xampp上使用Codeigniter,并尝试在视图中首次使用foreach,但我无法使其正常工作。

I'm using Codeigniter on an Apache xampp set up and attempting to use foreach in a view for the first time and I just can't get it to work.

我的控制器代码:

class Test extends CI_Controller {

        public function index($page = 'testv')
    {
            if ( ! file_exists(APPPATH.'/views/'.$page.'.php'))
            {
                show_404();
            }
                $this->load->model('testm');
                $data['news'] = $this->testm->get_news();

                $this->load->view('headder');
                $this->load->view($page, $data);
                $this->load->view('footer');
    }
}

我的模型:

class Testm extends CI_Model {

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

    Public function get_news()
    {
        $query = $this->db->query('SELECT id, date, text FROM news');

        foreach ($query->result_array() as $row)
        {
            echo $row['id'];
            echo $row['date'];
            echo $row['text'];
        }
    }
}

我的视图:

<main id='central_section'>
    <section id='logo_section'>
    <img src='<?php echo base_url(); ?>img/logo.png' id='small_logo' alt="Logo">
    </section>
    <section id='content'>
        <p class="large_headding">News</p>

            <?php foreach($news as $news) { ?>
                <article class="article_text">
                    <p class="segment_headding"><?php echo $news->date; ?></p>
                        <?php echo $news->text; ?>
                </article>
            <?php } ?>
        <div id="spacer"></div>
    </section>
</main>

目前,我收到以下警告消息:

At present I get the following warning message:

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/testv.php

Line Number: 18

Backtrace:

File: C:\xampp\htdocs\tsh\CI\application\views\testv.php
Line: 18
Function: _error_handler

File: C:\xampp\htdocs\tsh\CI\application\controllers\test.php
Line: 16
Function: view

File: C:\xampp\htdocs\tsh\public_html\index.php
Line: 292
Function: require_once

但是数据库中的文本确实出现在页眉顶部之外的页面顶部,因此我知道数据库正在连接并且正在收集数据库中的数据。谁能告诉我我要去哪里错了?

But the text from my database does appear at the top of the page outside of the headder so I know the database is connecting and the data from it is being collected. Can anyone tell me where I'm going wrong?

推荐答案

您在模型函数中遇到问题foreach循环只需将其替换为:

you just have issue in your model function foreach loop just replace that with:

$query = $this->db->query('SELECT id, date, text FROM news');
$result = $query->result_array();
return $result;

这篇关于Codeigniter在视图中使用foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆