Codeigniter回显结果在视图中

时间:2017-09-26 03:12:29

标签: php codeigniter

如何在我的视图中调用结果?

print_r给了我Array ( [0] => 2017-09-25 [1] => 2017-09-27 )

在我的视图文件中

echo $coachact->session_date给了我"non-object"

echo $session_date给了我"undefined variable"

控制器代码

public function editview($user_fname)
{
    $returnData = array();
    $this->load->model('User_model');
    $this->User_model->checkIfLoggedIn();

    $this->load->view('incf/header');
    $this->load->view('schedulef/sced_tools');

    $this->load->model('Schedule_model');
    $coachact = $this->Schedule_model->get($user_fname);
    if(!empty($coachact)){
        $returnData['coachact'] = $coachact;
        $returnData['user_fname'] = $user_fname;      
    }
    $this->load->view('schedulef/Schedule_manage',$returnData);
    //print_r($coachact);exit();
}

模型

public function get($user_fname)
{
    $returnArray = array();
    $query = $this->db->query("SELECT * FROM sessions WHERE user_fname = ?", ['user_fname' => $user_fname]);
    foreach ($query->result() as $row) {
        array_push($returnArray, $row->session_date);
    }
    return $returnArray;
}

2 个答案:

答案 0 :(得分:1)

在您的控制器代码中进行如下更改:

public function editview($user_fname)
{
    $returnData = array();
    $this->load->model('User_model');
    $this->User_model->checkIfLoggedIn();

    $this->load->view('incf/header');
    $this->load->view('schedulef/sced_tools');

    $this->load->model('Schedule_model');
    $coachact = $this->Schedule_model->get($user_fname);
    if(!empty($coachact)){
        $returnData['coachact'] = $coachact;
        $returnData['user_fname'] = $user_fname;        
    }
    $this->load->view('schedulef/Schedule_manage',$returnData);

}

并在视图文件中直接访问值为

<?php echo $coachact; ?>

并且

<?php echo $user_fname; ?>

您在左上角得到的输出是由于模型文件中的echo语句。

这是你的模态代码:

public function get($user_fname)
    {
        $returnArray['sesdate'] = array();
        $query       = $this->db->query("SELECT * FROM sessions WHERE user_fname = ?", ['user_fname' => $user_fname]);

        foreach ($query->result() as $row)
        {                  
          $sesdate = strtotime($row->session_date);
          $sesdate = date("Fj Y",$sesdate);
          array_push($returnArray['sesdate'], $sesdate);
        }   
        return $returnArray;
    }

由于有多个结果,您必须在视图文件中使用循环。

答案 1 :(得分:1)

  

在我看来文件echo $ coachact-&gt; session_date给了我“非对象”   echo $ session_date给了我“未定义的变量”

如下所示,在您的代码中,您要发送数组以进行查看

$coachact = $this->Schedule_model->get($user_fname);
if(!empty($coachact)){
    $returnData['coachact'] = $coachact;
    $returnData['user_fname'] = $user_fname;      
}
$this->load->view('schedulef/Schedule_manage',$returnData);

因此,在您看来,您将拥有2个变量:

$coachact 
$user_fname

要打印$user_fname的内容,您只需

echo $user_fname;

要查看您具有以下访问权限的$coachact数组的内容

echo $coachact[0];  // gives first element

循环结果

<?php foreach($coachact as $key => $value): ?>
         <p><?php echo $key. '=>' . $value;?></p>
<?php endforeach;?>