[英]How to return an object instead of array in Codeigniter?
當我嘗試獲取對象返回時,我在 Codeignter 中遇到了一個問題,一些控制器代碼是
$sql = $this->user_model->userdetail($data);
if ($sql) {
echo json_encode(array(
"status" => "0",
"message" => "",
"data" => $sql
));
exit();
}
型號代碼是
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();
}
我可以得到結果
{
"status": "0",
"message": "",
"data": [
{
"email": "lily@email.com",
"name": "lily"
}
]
}
這里的data
是一個數組,但它應該是一個對象,上面的結果應該是這樣的
{
"status": "0",
"message": "",
"data": {
"email": "lily@email.com",
"name": "lily"
}
}
我改變了return $query->result_array();
return $query->result_object();
在模型代碼中,但它不起作用,我該怎么辦? 非常感謝。
您的問題是您正在使用result_array() 。 您必須改用row() , row()函數將為您提供對象而不是數組。
型號代碼:
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;
}
我想我在模型中找到了原因
return $query->result_array(); // also can be changed to return $query->result_object(); or return $query->result();
它們可以返回數組或對象,並在控制器文件中
$sql = $this->user_model->userdetail($data);
$sql
應該是數組或對象,但實際上它返回一個像這樣的多維數組
返回結果()或結果對象()
Array
(
[0] => stdClass Object
(
[email] => lily@email.com
[name] => lily
)
)
返回結果數組()
Array
(
[0] => Array
(
[email] => lily@email.com
[name] => lily
)
)
真奇怪。
在代碼點火器中$query->result_array();
用於以數組格式返回結果。
要以對象格式獲取結果,請使用$query->result();
喜歡
if ($query->num_rows() > 0) {
return $query->result();
}
對於單行使用$query->result_array()
也許您需要 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.