在 php 中,返回一个数组的接口可以通过如下步骤来实现:
- 定义一个数组并填充数据。
$response = array(
'status' => 200,
'message' => '请求成功',
'data' => array(
'username' => 'tom',
'age' => 25,
'email' => 'tom@example.com'
)
);- 使用
json_encode()函数将数组转换为 JSON 格式的字符串。
$json = json_encode($response);
- 设置响应头,让客户端知道返回的是 JSON 数据。
header('Content-Type: application/json');- 输出 JSON 数据。
echo $json;
完整代码如下:
$response = array(
'status' => 200,
'message' => '请求成功',
'data' => array(
'username' => 'tom',
'age' => 25,
'email' => 'tom@example.com'
)
);
$json = json_encode($response);
header('Content-Type: application/json');
echo $json;当客户端请求该接口时,会收到一个包含以上数据的 JSON 格式字符串。客户端可以使用相应的方法将 JSON 数据解析为对象或数组,以便使用其中的数据。











