以下是用户列表webservice的json响应的代码。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Webservice extends CI_Controller
{
function list_user()
{
$result_login = $this->db->get('user_registration')->result();
$response = array();
$response ["success"] = 1;
$response ["message"] = "User List.";
foreach($result_login as $row)
{
$data = array();
$data['User Id'] = $row->user_id;
$data['Name'] = $row->name;
$data['Email'] = $row->email;
$data['mobile_number'] = $row->mobile_number;
$data['Password'] = $row->password;
$output2 = json_encode(array('responsedata' => $data));
echo $output2;
}
}
}
?>
在我的代码中,如果我在json_encode中用$ response替换$ data,那么我就无法获得$ data的值。 我以这种格式得到了json的回应。 JSON响应。
{
"responsedata": {
"User Id": "7",
"Name": "bhavin",
"Email": "bhavin123@gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
}
但我想以这种格式回复json。
{
"responsedata":
{
"success": 1,
"data": [
{
"User Id": "7",
"Name": "test",
"Email": "test1@gmail.com",
"mobile_number": "123456789",
"Password": "abc"
},
{
"User Id": "8",
"Name": "test2",
"Email": "test2@gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
]
}
}
答案 0 :(得分:3)
您需要像这样排列您的数组
我更新以下代码
$array_of_event = array()
foreach($result_login->result_array() as $row)
{
$array_of_event[] = $row;
}
$data['success'] = "1";
$data['data'] = $array_of_event; //need to assign event here
$response['responsedata'] = $data;
echo json_encode($response);