我是 php 新手,正在嘗試以特定結構回傳 json 回應。這是我到目前為止所嘗試的:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x ;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
上面的代碼回傳這個回應:

但是,我不想將“branchId”和“branch”作為單獨的屬性回傳,而是希望將它們的值傳遞到 branchObject 中,例如 branch.id == “branchId”和 branch.name == “branch”。我的意思是,如何以以下結構回傳回應:

這是我的資料庫的樣子:
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您要求我們不確定 db result 是否回傳但正如 nice_dev 指出的那樣,您需要這樣的東西:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x ;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471296.html
上一篇:Tomcat的普通加載器不能參考WEB-INF/lib里面的jar嗎?
下一篇:SQL更新表,其中關系在其他表中
