dpy83214 2017-07-16 16:53
浏览 45
已采纳

如何获取数组而不是json对象?

<?php 

$link = mysql_connect('localhost', 'root', 'admin')
or die('There was a problem connecting to the database.');
mysql_select_db('hospitalmaster');

$hnum = (int)$_POST["hnum"];
$sql = "SELECT d.doctorid, d.doctorname 
        from hospitalmaster.doctor_master d 
            inner join pharmacymaster.pharbill e 
        where e.hnum = '$hnum' 
        and e.presid = d.d_empno 
        group by e.presid";

$result = mysql_query($sql);
$response = array();

if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $response = $row;
    }

    echo json_encode(array("Doctor"=>$response));
} else {
    echo ("no DATA");
}
?>

i have the api shown above, but this api is returning me as json objects not an json array? i would like to know how to get dotorid an doctorname as a array, since i have many doctor names and id, i want each doctor and their corresponding id as an idividual array, right now they are returning as individual objects. Since this is my first time writing an api, i dont know how to modify the code.

  • 写回答

1条回答 默认 最新

  • dousao6260 2017-07-16 16:56
    关注

    You are over writing the array each time round the loop.

    while ($row = mysql_fetch_assoc($result)) {
        $response[] = $row;
        //change ^^
    }
    

    You should use either mysqli_ or PDO. Here is a suggestion for mysqli_

    <?php 
    
    $link = mysqli_connect('localhost', 'root', 'admin','hospitalmaster')
    or die('There was a problem connecting to the database.');
    
    $sql = "SELECT d.doctorid, d.doctorname 
            from hospitalmaster.doctor_master d 
                inner join pharmacymaster.pharbill e 
            where e.hnum = ?
            and e.presid = d.d_empno 
            group by e.presid";
    
    $stmt = $link->prepare($sql);
    $stmt->bind_param('i', (int)$_POST["hnum"]);
    $stmt->execute();
    
    if ($stmt->num_rows() > 0) {
        $result = $stmt->get_result();
        $response = array();
    
        while ($row = $result->fetch_assoc()) {
            $response[] = $row;
        }
    
        echo json_encode(array("Doctor"=>$response));
    } else {
        echo ("no DATA");
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder出现这样的报错
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上