2013-05-02 70 views
1

我想将数组传递到视图页面并将项目放在列表框/下拉列表中。我在哪里错了这个代码?CodeIgniter - 从模型发送数组到控制器到页面

型号

public function get_suppliers(){ 
     $type = "SUPPLIER"; 
     $this->db->where('usertype', $type); 
     $query = $this->db->get('users'); 
     foreach ($query->result() as $row){ 
      $results = array(
       'userid' => $row->userid, 
       'firstname' => $row->firstname, 
       'lastname' => $row->lastname, 
       'company' => $row->company 
      ); 

     } 
     return $results; 
    } 

控制器

$this->load->model('user_model'); 
$data['supplier']= $this->user_model->get_suppliers(); 
$this->load->view('include/header.php'); 
$this->load->view('addvehicle_view', $data); 
$this->load->view('include/footer.php'); 

查看

<?php 
    if(isset($supplier)){ 
     foreach ($supplier as $info){ 
     echo'<option value="' . $info->userid . '">' . $info->company . ' - ' . $info->lastname . ', ' . $info->firstname . '</option>'; 
    } 
    } 
    ?> 

回答

3

get_suppliers()

$results = array(); // just in case there is no record 

foreach (...) { 
    $results[] = array(// you forgot the "[]" 
     ... 
    ); 
} 

另一个问题:你的模型(一旦修复)返回一个数组数组,而你的视图需要一个对象数组。

开门见山,这里是你的新性感模特方法:

public function get_suppliers() { 
    return $this->db 
     ->where('usertype', 'SUPPLIER') 
     ->get('users') 
     ->result(); 
} 
+0

我在视图页面使用的var_dump转储阵列和下面是我得到了什么,但它不是在foreach正确抽取循环。你是否在视图中看到每个循环的问题? (1){[0] => array(4){[“userid”] => string(1)“3”[“firstname”] => string(13)“SupplierFirst”[“lastname”] =>字符串(12)“SupplierLast”[“company”] => string(9)“Supply Co”}} – jfur7 2013-05-02 23:51:44

+0

看起来您没有阅读我的答案。我只是编辑它来添加一个现成的代码。 – 2013-05-03 03:04:17

+0

谢谢你的帮助:)工作很好! – jfur7 2013-05-03 04:50:43

0
public function get_suppliers(){ 
    $type = "SUPPLIER"; 
    $this->db->where('usertype', $type); 
    $query = $this->db->get('users'); 
    $results = array(); 
    foreach ($query->result() as $row){ 
     $results[] = array(
       'userid' => $row->userid, 
       'firstname' => $row->firstname, 
       'lastname' => $row->lastname, 
       'company' => $row->company 
     ); 

    } 
    return $results; 
} 
相关问题