CodeIgniter - 从模型到控制器到页面发送数组

时间:2013-05-02 23:40:33

标签: php arrays 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>';
    }
  }
  ?>

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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;
}