首页 > 解决方案 > 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 的代码?

谢谢。

标签: phpmysqljson

解决方案


只是 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);

推荐阅读