0

CIでこのエラーが発生しました:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: news

Filename: controllers/First.php

Line Number: 33

A PHP Error was encountered



Severity: Notice

Message: Undefined variable: news

Filename: views/welcome_view.php

Line Number: 1

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/welcome_view.php

Line Number: 1

私のコントローラーがあります:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

   class First extends CI_Controller
   {
    
    public function __construct()
    {
    parent::__construct();
    $this->load->model('materials_model');
    }    
    
    
    public function index()
      {
        $this->load->view('header_view');
        $this->load->view('menu_view');
        $this->load->view('about_me_view');
        $this->load->view('navigation_view');
        $this->load->view('search_view');
        $this->load->view('main_text_view');
        $this->load->view('footer_view');
       
      }
  
   
    public function mat()
    {
       $this->load->model('materials_model');
       $this->materials_model->get();
       $data['news'] = $this->materials_model->get();
    
       $this->load->view('welcome_view',$news);
    
       if(empty($data['news']))
       {
        echo'Array is Null';
       }
    
       else
       {
        echo'Array has info';
       }
    }

私のモデル:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

class Materials_model extends CI_Model
{
    public function get()
    {
        $query = $this->db->get('materials');
        return $query->result_array();
    }

     
}

?>

私の見解 :

<?php foreach ($news as $one):?>
<?=$one['author']?>
<?php endforeach; ?>

ビューに渡す配列はNULLではありません(print_rをチェックし、そうでない場合は構造をチェックします)が、それを渡して表示することはできます。どんな間違いがありますか?

4

3 に答える 3

0
$this->load->view('welcome_view',$news);

$news定義されることはありません。たぶんあなたは?を使うつもり$dataですか?、CIビューはassoc配列がそれらに渡されることを期待しています。

于 2012-08-08T11:33:22.843 に答える
0

変数を設定します:

$data['news'] = $this->materials_model->get();

ビューに渡します:

$this->load->view('welcome_view', isset($data) ? $data : NULL);

結果配列としてビューでアクセスします。

<?php 
    foreach($news as $item)
    {
        echo $item['id']." - ".$item['some_other_column_title']
    } 
?>

オプションとして、モデルのget()メソッドを変更して、配列ではなくオブジェクトを返すことができます。

public function get()
{
    $query = $this->db->get('materials');
    return $query->result();
}

次に、ビューでは、次のように$newsをオブジェクトとして処理する必要があります。

<?php 
    foreach($news as $item)
    {
        echo $item->id." - ".$item->some_other_column_title
    } 
?>
于 2012-08-08T11:38:32.777 に答える
0

コントローラでは、ニュースではなくデータを渡す必要があります

$data['news'] = 'Something';
$this->load->view('welcome_view',$data);

そしてあなたの見解ではあなたは使うことができます

foreach($news as $new)
{
   //Go Here
} 
于 2012-08-22T12:05:36.040 に答える