[英]How to return this Multidimensional PHP Array as a JSON object?
I have this code in my model when the controller requests to get all the messages for a certain user: 当控制器请求获取特定用户的所有消息时,我的模型中有以下代码:
public function get_messages($user_id) {
$sql = "SELECT *
FROM messages
WHERE `to` = '$user_id'
ORDER BY id DESC";
$query = $this->db->query($sql);
foreach($query->result() as $row) {
$messages[] = array(
'id' => $row->id,
'to' => $row->to,
'from' => $row->from,
'message' => $row->message,
'star' => $row->star,
'timestamp' => $row->timestamp
);
}
return $messages;
}
Here's the code in my controller: 这是我的控制器中的代码:
$result = $this->inbox_m->get_messages($user['id']);
How can I return the result as a JSON object using PHP's json_encode()
function? 如何使用PHP的json_encode()
函数将结果作为JSON对象返回?
Normally I do something like this for simple returns: 通常我会为简单的回报做这样的事情:
json_encode(array('result' => true))
but all these arrays in arrays got me confused. 但是数组中的所有这些数组让我感到困惑。
Never mind guys, should have actually tried it before posting. 没关系,在发布之前应该已经尝试过了。 This works just fine: 这很好用:
echo json_encode(array('result' => $result));
I will close the question in a day when my account allows me. 如果帐户允许我在一天之内解决问题。
json_encode($messages);
should be fine here. 这里应该很好。 Call it and examine the output to see if it's what you want. 调用它并检查输出以查看是否正是您想要的。 But json_encode
should handle nested arrays without breaking a sweat. 但是json_encode
应该处理嵌套数组而不会费力。
Closing the question by answering it myself. 通过自己回答来结束问题。 Like explained in the edit this works just fine: 就像编辑中解释的那样,它可以正常工作:
echo json_encode(array('result' => $result));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.