Codeingniter3 回显关联数组的单个元素


Codeingniter3 echo a single element of an associative array

假设我有这个控制器函数

public function index(){
    $this->load->model('model_users');
    $clienteemail = $this->session->userdata('email');
    $cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
    $data['title']='La Giumenta Bardata Dashboard'; //array per titolo e dati passati
    $this->load->view('auth/template/auth_header', $data);
    $this->load->view('auth/template/auth_nav', $cliente);
    $this->load->view('auth/clienti/auth_sidebar');
    $this->load->view('auth/clienti/client_dash');
    $this->load->view('auth/template/auth_footer');
}

model_users是使用此函数查询数据库的模型:

public function lettura_dati($clienteemail)
{
  $this->db->where('email', $clienteemail);
  $query = $this->db->get('user');
  if ($query) {
    $row = $query->row();
    $cliente['nome'] = $row->nome;
    return $cliente;
  } else {
    echo "errore nella ricerca del nome";
  }

我正在尝试做的是使用会话数据中的用户电子邮件从数据库表中检索信息。

所以我开始只检索用户的名称。该函数有效,但是在视图中我使用echo $nome;

我有一个关于数组和字符串之间转换的错误......我知道这很正常,但如果我这样做

print_r($nome); 

我的输出是:Array[0] => 'Pippo'

我只想输出数组的内容。我怎样才能做到这一点?

看起来你有点错别字。

您的型号:

$row = $query->row(); // Fetch the entireuser
$cliente['nome'] = $row->nome; // Set the name to a value. $cliente isn't defined yet..
return $cliente; // Return the entire $cliente array.

您的控制器:

您正在使用上述模型方法,并假设它只返回名称。它实际上是返回完整用户。

$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);

将模型代码更改为以下内容,它应该按预期工作。

public function lettura_dati($clienteemail)
{
  $this->db->where('email', $clienteemail);
  $query = $this->db->get('user');
  if ($query && $query->num_rows() > 0) { // Ensure we have got at least 1 row
    $row = $query->row();
    return $row->nome;
  } else {
    echo "errore nella ricerca del nome";
  }
}
return $row->nome;

而不是:

$cliente['nome'] = $row->nome;
return $cliente;

$cliente_data = $this->model_users->lettura_dati($clienteemail);
$cliente['nome'] = $cliente_data['nome'];

而不是:

$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);