[英]Converting a Mysql Result Object to Associative Array (CodeIgniter)
我正在尝试获取数据库查询,这是一个转换为关联数组的对象,以便我可以在codeigniter中的日历类中使用它。
这是我的模特:
<?php
class Get_diary_model extends Model {
function getAllDiaries($year,$month) {
$data = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year"); // the entries for the relevant month and year
foreach($data->result_array() as $row) { // return result as assoc array to use in calendar
echo $row['day'];
echo $row['entry'];
}
return $data;
}
}
这是我得到的错误:
atal error: Cannot use object of type CI_DB_mysql_result as array in C:\wamp\www\mm\system\libraries\Calendar.php on line 219
有任何想法吗?
看看这个视频教程,它会对你有所帮助 - > http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-the-calendar-library/
您的模型应如下所示:
function getAllDiaries($year,$month)
{
$q = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year");
if($q->num_rows() > 0):
foreach($q->result() as $row):
$data[] = $row;
endforeach;
return $data;
else:
return false;
endif;
}
和你的控制器:
function index($year = null, $month = null)
{
$this->load->model('Get_diary_model');
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$data['calendar'] = $this->Get_diary_model->getAllDiaries($year, $month);
}
问题不在于你使用result_array(),而是你以后直接返回$ data。 $ query = $ this-> db-> query()然后在foreach中使用$ query-> result_array()。 然后,您可以在foreach中构建后返回$ data。
另一个答案是编写以下内容的冗长方式:
function getAllDiaries($year,$month)
{
$sql = "SELECT day AND entry FROM diary WHERE month=$month AND year=$year";
return $this->db->query($sql)->result();
}
但是当然会返回一个对象数组,而不是多维数组。
使用以下简单方法,
$query = $this->db->get_where('table', array('table_id' => $id));
$queryArr = $query->result();
foreach ($queryArr[0] as $key=>$val)
{
$row[$key]=$val;
}
print_r($row); //this will give associative array
这是CodeIgniter-3的解决方案
function getAllDiaries(){
$query = $this->db->query("YOUR QUERY HERE");
return $query->result('array');
}
要么
function getAllDiaries(){
return $this->db->query("YOUR QUERY HERE")->result('array');
}
注意: result()函数接受“array”或“object”作为参数。 默认为“对象”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.