我有一个数据库(字段)与行:ID, field_name, field_label.
我想建立一个包含所有avail记录的数组。
fields_model is:
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吗?。由于
In model
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'];
}
使用此代码-
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;
}
删除这一行
$fields = array();
希望对您有所帮助:
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;
}