[英]How to get an array instead of json object?
<?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");
}
?>
我有上面显示的api,但这个api返回我作为json对象而不是json数组? 我想知道如何将dotorid作为一个阵列的医生名称,因为我有很多医生的名字和身份证,我希望每个医生和他们相应的身份证作为一个单独的数组,现在他们作为单独的对象返回。 由于这是我第一次编写api,我不知道如何修改代码。
你每次循环都在编写数组。
while ($row = mysql_fetch_assoc($result)) {
$response[] = $row;
//change ^^
}
你应该使用
mysqli_
或PDO。 这是对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");
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.