Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么CodeIgniter以数组的形式返回我的SQL查询,其中包含一个对象?_Php_Mysql_Codeigniter - Fatal编程技术网

Php 为什么CodeIgniter以数组的形式返回我的SQL查询,其中包含一个对象?

Php 为什么CodeIgniter以数组的形式返回我的SQL查询,其中包含一个对象?,php,mysql,codeigniter,Php,Mysql,Codeigniter,我在codeigniter中构建了一个名为“Profile_model”的模型,该模型包含以下sql查询,并应返回具有给定id的用户的用户名('userpdata'是包含此信息的表): 我已经像这样从控制器中传入了当前用户的$id(模型称为“profile”): 用户/配置文件查看: <?php print_r($username); ?> 这将返回字符串: 数组([0]=>stdClass对象([user\u name]=>hish)) 它似乎是一个包含对象的数组。如何

我在codeigniter中构建了一个名为“Profile_model”的模型,该模型包含以下sql查询,并应返回具有给定id的用户的用户名('userpdata'是包含此信息的表):

我已经像这样从控制器中传入了当前用户的$id(模型称为“profile”):

用户/配置文件查看:

<?php 
  print_r($username);
?>

这将返回字符串:

数组([0]=>stdClass对象([user\u name]=>hish))


它似乎是一个包含对象的数组。如何仅检索用户名'hish'

更改
$query->result()
$query->row()这样就不会得到数组。
result()
方法返回一个行数组,每个行都是一个对象。
row()
方法返回结果集的第一个对象

public function get_username($id)
{
  $query = $this->db->select('user_name')
                    ->where('id', $id)
                    ->get('userpdata');
  return $query->row();
}
您将得到包含属性
user\u name
的对象。您可以在控制器中获取它的值

$user = $this->profile->get_username($userId);
$data = array(
    'username' => $user->user_name
);
或者您可以在不更改控制器的情况下在视图中获取它,并使用此
$username->user\u name


通常,搜索结果总是一组数组或一组对象。毫无疑问,CI在检索结果时使用了它所选择的db库的“fetchObject()”函数。太棒了,我已经让它工作了。谢谢几分钟后我会接受你的回答。
public function get_username($id)
{
  $query = $this->db->select('user_name')
                    ->where('id', $id)
                    ->get('userpdata');
  return $query->row();
}
$user = $this->profile->get_username($userId);
$data = array(
    'username' => $user->user_name
);