2015-09-17 49 views
0

我有一個數據庫(字段)與行:ID, field_name, field_label. 我想建立一個數組與所有的有效記錄。Codeigniter上的SQL查詢

fields_model是:

public function getFields() { 
    $this->db->select('*')->from('fields'); 

    $query = $this->db->get(); 

    if (!$query->num_rows() > 0) { 
     die("Error"); 
    } 

    $fields = array(); 

    foreach ($query->result() as $row) { 
     $fields[$row->id]['nume'] = $row->field_name; 
     $fields[$row->id]['label'] = $row->field_label; 
    } 
    // Pass the result back to the controller 
    return $fields; 


} 

在控制器我有:

$this->load->model('fields_model'); 
    $data['fields'] = $this->fields_model->getFields(); 

但我得到:Message: Array to string conversion error 任何IDEEA?感謝

+0

請問,其上線,你得到的錯誤? –

+0

基本上這個錯誤「消息:數組到字符串轉換錯誤」意味着你正在嘗試回顯一個字符串,但是給出數組。嘗試使用print_r($ your_array_variable)來更好地理解。 – Jeremy

回答

0

刪除此行

$fields = array(); 
1

在模型

function getFields() 
    { 

     $query = $this->db->query("SELECT * from fields"); 
     $result = $query->result_array(); 
     return $result; 
    } 

在控制器

$this->load->model('fields_model'); 
    $data['fields'] = $this->fields_model->getFields(); 

    if (empty($data['fields'])) 
    { 
     echo "Empty data"; 
    } 
    else 
    { 
     return $result; 
    } 

鑑於

<?php 
    foreach ($fields as $new_item) 
    { 
     echo $new_item['nume']; 
     echo "<br/>"; 
     echo $new_item['label']; 
    } 
+0

只需用我的代碼替換所有代碼即可 –

1

使用此代碼 -

public function getFields() { 
    $this->db->select('*')->from('fields'); 

    $query = $this->db->get(); 

    if (!$query->num_rows() > 0) { 
     die("Error"); 
    } 

    $fields = array(); 

    foreach ($query->result() as $row) { 
     $fields[$row->id]['nume'] = $row->field_name; 
     $fields[$row->id]['label'] = $row->field_label; 
     $fields_array[]=$fields; 
    } 
    // Pass the result back to the controller 
    return $fields_array; 


} 
0

希望這有助於:

public function getFields() { 
    $query = $this->db->get('fields'); 
    $result = $query->result(); 

    $array = array(); 
    foreach($result as $field){ 
     $element = array(
      'nume' => $field->field_name, 
      'label'=> $field->field_label 
     ); 
     array_push($array, $element); 
    } 

    return $array; 
}