php sql 如何按照分组查询后分类输出为 json?
问题:
需要将数据库中的数据分组输出为 json 格式,但当前代码只实现了按照分类遍历输出的情况。如何改进代码来输出为 json?
改进方案:
- 初始化一个名为 $response 的数组,用以存放响应信息(包括响应码、消息、数据)。使用循环遍历分类表,为每个分类创建一个空元素 $item。为每个分类赋值 name 字段。再次使用循环遍历详情表,为每个详情赋值到 $item[‘list’] 数组中。将每个 $item 元素添加到 $result 数组中。将 $result 数组赋值给 $response[‘data’]。设置 content-type 为 application/json。使用 json_encode 将 $response 数组转为 json 字符串并输出。
改进后的代码:
$response = [ ‘code’ => 0, ‘msg’ => ‘ok’, ‘data’ => null,];$result = [];$queryClass = mysqli_query($conn, "SELECT cid,cname FROM class_wtool WHERE uid = ‘mon’");while ($rclass = mysqli_fetch_array($queryClass)) { $item = []; $item[‘name’] = $rclass[‘cname’]; $queryDetail = mysqli_query( $conn, "SELECT wid,simpleW,detailW FROM word_wtool WHERE uid = ‘mon’ AND cid = " . $rclass[‘cid’] ); while ($rdetail = mysqli_fetch_array($queryDetail)) { $item[‘list’][] = [‘wid’ => $rdetail[‘wid’],’simpleW’ => $rdetail[‘simpleW’],’detailW’ => $rdetail[‘detailW’], ]; } $result[] = $item;}$response[‘data’] = $result;header(‘Content-Type: application/json’);echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);die();
这样就可以将分组后的数据按照 json 格式输出。
以上就是PHP和SQL分组查询结果如何以JSON格式输出?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » PHP和SQL分组查询结果如何以JSON格式输出?