php - JSON:以不同格式显示 JSON 结果
问题描述
我只是 JSON 的新手。根据我的问题,以下是我当前的代码广告结果
代码 1
<?php
require_once '../config/configPDO.php';
header('Content-Type: application/json');
$response = array();
$badgeid = '10010080';
$pwd = '10010080';
$stmt = $conn->prepare("SELECT * FROM ot_users WHERE badgeid = '$badgeid' AND pwd = '$pwd' AND roles_id = 7 AND team_id <> 1");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $result;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
echo json_encode($response);
?>
结果 JSON 1
{"error":false,"message":"登录成功","user":{"badgeid":"10010080","email":null,"pwd":"10010080","fullname":"AZWAN BIN SANIMIN","roles_id":"7","team_id":"2","users_id":null}}
代码 2
<?php
header('Content-Type: application/json');
$response = array();
$badgeid = '10010080';
$pwd = '10010080';
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_displayUser?badgeid=$badgeid&pwd=$pwd";
$data = file_get_contents($url);
$json = json_decode($data);
$result = $json->otUserList;
if (!empty($result)) {
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $result;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
echo json_encode($response);
?>
结果 JSON 2
{"error":false,"message":"登录成功","user":[{"badgeid":"10010080","email":"","pwd":"","fullname":"AZWAN BIN SANIMIN","roles_id":"7","team_id":"2","users_id":""}]}
区别之一是“[”,结果 JSON 2 有它,而结果 1 没有。我在这里想要什么,我希望结果 2 与结果 1 相同。
谁能知道我需要在哪里更改代码 2 的代码?
谢谢。
解决方案
只是 php 变量将 $result 更改为 $result[0] 试试这个。无法执行您的“ http://172.20.0.45/TGWebService/TGWebService.asmx/ot_displayUser?badgeid=$badgeid&pwd=$pwd ”链接,因为密码不正确
header('Content-Type: application/json');
$response = array();
$badgeid = '10010080';
$pwd = '10010080';
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_displayUser?badgeid=$badgeid&pwd=$pwd";
$data = file_get_contents($url);
$json = json_decode($data);
$result = $json->otUserList;
if (!empty($result)) {
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $result[0];
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
echo json_encode($response);
推荐阅读
- php - 如何将根域存储为 php 中的变量并使用它在文件夹之间移动
- php - Apache Unicode 处理
- database - Flutter:将数据从第一屏发送到第二屏
- amazon-web-services - 错误无法为无服务器自定义域设置基域映射
- javascript - Nativescript-vue TabView 无法呈现来自 API 的第一个项目
- regex - 用于匹配整个特定 IP 地址类集的 RegEx 模式?
- string - 从字符串转换时如何确定 []rune 的容量
- django - Django 部署:错误 403 Forbidden 您无权访问此服务器上的 /
- r - 如何迭代匹配单词序列
- javascript - 如何在过滤后的 Observable 上设置值