[英]How to return an object instead of array in Codeigniter?
I meet a question in Codeignter when I try to get an object return, some of controllers codes are当我尝试获取对象返回时,我在 Codeignter 中遇到了一个问题,一些控制器代码是
$sql = $this->user_model->userdetail($data);
if ($sql) {
echo json_encode(array(
"status" => "0",
"message" => "",
"data" => $sql
));
exit();
}
And the model codes are型号代码是
function userdetail($data) {
$id = $data["id"];
$sql = "select email, name from user where id='".$id."'";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
return $query->result_array();
}
return $query->num_rows();
}
I can get the result我可以得到结果
{
"status": "0",
"message": "",
"data": [
{
"email": "lily@email.com",
"name": "lily"
}
]
}
here the data
is an array, but it should be an object, the above result should like this这里的
data
是一个数组,但它应该是一个对象,上面的结果应该是这样的
{
"status": "0",
"message": "",
"data": {
"email": "lily@email.com",
"name": "lily"
}
}
And I changed return $query->result_array();
我改变了
return $query->result_array();
to return $query->result_object();
return $query->result_object();
in model code, but it doesn't work, what should I do here?在模型代码中,但它不起作用,我该怎么办? Thanks a lot.
非常感谢。
Your problem is you are using result_array() .您的问题是您正在使用result_array() 。 You have to use row() instead, row() function will give you the object instead of array.
您必须改用row() , row()函数将为您提供对象而不是数组。
The model code:型号代码:
function userdetail($data) {
$id = $data["id"];
$sql = "select email, name from user where id='".$id."'";
$query = $this->db->query($sql);
return $query->num_rows() > 0 ? $query->row() : 0;
}
I think I find the reason, in model我想我在模型中找到了原因
return $query->result_array(); // also can be changed to return $query->result_object(); or return $query->result();
They can return array or object, and in controller file它们可以返回数组或对象,并在控制器文件中
$sql = $this->user_model->userdetail($data);
$sql
should be array or object, but actually it return a Multidimensional Arrays like this $sql
应该是数组或对象,但实际上它返回一个像这样的多维数组
return result() or result_object()返回结果()或结果对象()
Array
(
[0] => stdClass Object
(
[email] => lily@email.com
[name] => lily
)
)
return result_array()返回结果数组()
Array
(
[0] => Array
(
[email] => lily@email.com
[name] => lily
)
)
it's strange.真奇怪。
In codeigniter $query->result_array();
在代码点火器中
$query->result_array();
is used to return result in array Format.用于以数组格式返回结果。
To get result in object format use $query->result();
要以对象格式获取结果,请使用
$query->result();
like喜欢
if ($query->num_rows() > 0) {
return $query->result();
}
For single row use $query->result_array()
对于单行使用
$query->result_array()
Maybe you need JSON_FORCE_OBJECT in json_encode.也许您需要 json_encode 中的 JSON_FORCE_OBJECT。
echo json_encode(array(
"status" => "0",
"message" => "",
"data" => $sql), JSON_FORCE_OBJECT);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.