我正在使用Codeigniter,并尝试将一个查询的结果传递给第二个。我收到错误
"致命错误:无法使用CI_DB_mysql_result类型的对象作为数组"。
任何建议将不胜感激。 对于我的$ truck_num查询,我只是在一个名为truck_num的字段中获取卡车列表。然后我试图将这些结果传递给进行一些计算的查询。
控制器 ///////////
function average_battery_life_by_truck() {
$truck_num = $this->mhedash_model->select_truck();
foreach($truck_num->result_array() as $row) {
$array = $row['truck_num'];
$results[] = $this->mhedash_model->select_battery_life_truck($array);
}
$data['array'] = $results;
$data['main_content'] = 'mhe/average_truck_bat';
return $this->load->view('includes/template',$data);
}
查看 //////
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<p><h1></h1></p>
<FORM
<></div>
<br />
<p><h4 id="date"></h4></p>
<h3></h3>
<table id="table" class="sortable">
<THEAD>
<TR>
<TH>Truck</TH>
<TH>Average Hours</TH>
</TR>
</THEAD>
<TBODY>
<?php $count = 0; ?>
<?php foreach($array as $row): ?>
<TR >
<TD><?php echo $row['average_bat_life']; ?></TD>
<TD><?php echo $row['truck_num']; ?></TD>
</TR>
<?php $count++; ?>
<?php endforeach;?>
</TBODY>
</table>
MODEL /////
function select_truck() {
mysql_select_db('battery');
$this->table_name = 'truck';
$truck_num = "SELECT
truck_num
FROM
truck
WHERE
battery_type_id = '5'
or battery_type_id = '8'
or battery_type_id = '10'
or battery_type_id = '9'
ORDER BY truck_num
";
return $this->db->query($truck_num);
}
function select_battery_life_truck($data) {
mysql_select_db('battery');
$this->table_name = 'truck_hours';
$truck_num = $this->db->escape($data);
/*This query takes the current row's metered hours and subtracts it with the previous row's metered hours.
We then average out the time the battery was on the truck for the date range */
$query = "SELECT
ROUND(AVG(metered_hours-b),2) average_bat_life,
truck_num
FROM (SELECT
id,
metered_hours,
loc_id,
(SELECT MAX(metered_hours)
FROM
(SELECT @rownum:=@rownum+1 id, truck_hours.metered_hours,truck_hours.loc_id from truck_hours,truck, (SELECT @rownum:=0) r where truck_hours.loc_id = truck.loc_id and truck.truck_num = $truck_num and DATE_SUB(CURDATE(),INTERVAL 30 DAY) >= truck_hours.ctrl_date ) a
WHERE a.metered_hours < t.metered_hours)b
FROM
(SELECT @rownum:=@rownum+1 id, truck_hours.metered_hours,truck_hours.loc_id from truck_hours,truck, (SELECT @rownum:=0) r where truck_hours.loc_id = truck.loc_id and truck.truck_num = $truck_num and DATE_SUB(CURDATE(),INTERVAL 30 DAY) >= truck_hours.ctrl_date ) AS t) c,
truck
WHERE c.loc_id = truck.loc_id
ORDER BY average_bat_life";
return $this->db->query($query);
}
答案 0 :(得分:1)
在第二个查询中,您无法从数据库中获取数据。
所以你需要添加fetch方法
在您的控制器中
foreach($truck_num->result_array() as $row) {
$array = $row['truck_num'];
$result = $this->mhedash_model->select_battery_life_truck($array);
foreach($result->result_array() as $row_data) {
$results[] = $row_data;
}
}
$data['array'] = $results;
$data['main_content'] = 'mhe/average_truck_bat';
$this->load->view('includes/template',$data);