php 为什么我在 CodeIgniter 中收到“数组到字符串转换”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16631533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting an "array to string conversion" error in CodeIgniter?
提问by mabbs
I'm currently having a problem with this error:
我目前遇到此错误的问题:
array to string conversion
数组到字符串的转换
Here's the code:
这是代码:
controller:
控制器:
function get_tariff()
{
$this->load->model('model_tariff');
$data['destination']=$this->input->post('dest',true);
$data['lines']=$this->input->post('lines',true);
$data['weight']=$this->input->post('weight',true);
$data['priceperkg']=$this->model_tariff->get_tariff();
$data['pricetotal']=$data['priceperkg']* $data['weight'];
$this->load->view('tariff_result',$data);
}
model:
模型:
function get_tariff()
{
$destination=$this->input->post('dest');
$lines=$this->input->post('lines');
$weightt=$this->input->post('weight');
$this->db->select('price');
$this->db->from('view_tariff');
$this->db->where('city_name',$destination);
$this->db->where('lines',$lines);
$price=$this->db->get();
return $price->result();
}
view:
看法:
Price per kg <?php echo $priceperkg?>;
Bayar total <?php echo $pricetotall?>;
回答by Wolf
The CodeIgniter database method result()
returns an array of objects, not a string literal (price). You need to do some further transformations. For example, if you are expecting a single row, then try row()
which returns a single object. In turn, you can then reference the property price
:
CodeIgniter 数据库方法result()
返回一个对象数组,而不是字符串文字(价格)。你需要做一些进一步的转换。例如,如果您期望单行,则尝试row()
which 返回单个对象。反过来,您可以引用该属性price
:
return $price->row()->price;
Or, you can treat this several other ways.
或者,您可以通过其他几种方式处理此问题。
回答by Kailash Yadav
Read CodeIgniter Active Result function
This function returns the query result
as an array of objects, or an empty arrayon failure. Typically you'll use this in a http://ellislab.com/codeigniter/user-guide/database/results.html, like this:
此函数返回query result
一个对象数组,或者失败时返回一个空数组。通常,您将在http://ellislab.com/codeigniter/user-guide/database/results.html 中使用它,如下所示:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
The above function is an alias of result_object().
上述函数是result_object()的别名。
If you run queries that might not produce a result, you are encouraged to test the result first:
如果您运行的查询可能不会产生结果,我们鼓励您先测试结果:
$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
}