PHP错误信息:数组到字符串的转换


A PHP Error Message: Array to string conversion

我是一个新手,只是我得到了这个错误:

A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/coba.php
Line Number: 52

我还是解不出来。这是我在控制器上的代码:

public function getvalue()
{
 $result = $this->admin_model->harga();
 $data = array(
        'harga' => $result,
    );
 if ($this->input->post('btnKirim')==true) {
  $data['nama']=$this->input->post('nama');
  $data['tgl_masuk']=$this->input->post('tgl_masuk');
  $data['tgl_ambil']=$this->input->post('tgl_ambil');
  $data['berat']=$this->input->post('berat');
  $data['status']=$this->input->post('status');
 }
 $data['judul'] = 'Halaman Pegawai';
 $data['content'] = 'coba';
 $this->load->view('template/index',$data);
}

和我的模型的代码:

public function harga(){
    $query= $this->db->query('SELECT harga from satuan');
    return $query->result();
}

这是我的视图。php在哪里我得到这个错误信息:

<div class="form-group">
<label for="total" class="control-label">Total Harga</label>
<div>
    <input name="total" id="total" type="numeric" class="form-control" value="<?php echo $harga; ?>" readonly='total'>
</div>
</div>

为什么我得到这个消息,我能做些什么来解决它?

方法result返回一个对象数组或一个空数组。无论哪种方式,方法harga返回一个数组。

由于您正在使用该结果来填充字段的值,因此不清楚您是否真的想要来自表的所有结果或只是一些特定的结果,甚至可能只有一个结果。无论你想要什么,你都需要将其转换为标量值,以便能够使用echo而不发出警告。

可以对返回的结果进行迭代,因此可以这样做:

public function harga() {
    // Since your HTML containts 'Total harga', I'm assuming you
    // have multiple results and you need to add them all up
    $result = 0
    foreach($query->result() as $row) {
        $output += $row->harga;
    }
    return $result;
}

如果您只需要一个结果,请考虑使用$query->row()从表中获取单行(更好的是,在sql查询中使用limitwhere)。

要完全了解您的问题是什么,请查看文档

你可以试试code:

$result = $this->admin_model->harga();
foreach($query->result() as $row) {
    $data['harga']= $row->harga;
}