如何获得像这样的嵌套pojo结果
object
------object
------object
------------object
------array
这是我从一个忘记的地方得到的,但是它没有代码来实现此结果。
{
"success": true,
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
"pie_statistics": {
"assigned": 120,
"opened": 212,
"in-progress": 100,
"completed": 320,
"done": 433,
"rejected": 111,
"expired": 332
},
"bar_months":[
"jan",
"feb",
"mar"
],
"bar_pending":[
100,
200,
300
],
"bar_rejected":[
140,
220,
340
],
"bar_completed":[
170,
290,
310
]
}
使用这样的代码
<?php
require "connection.php";
$query = "SELECT a.kondisi, k.area, COUNT(k.area) AS carea, COUNT(k.nrp) AS cnrp
FROM tb_absens AS a
INNER JOIN tb_karyawans AS k
ON a.nrp = k.nrp
WHERE a.kondisi = 'Sehat'
GROUP BY k.area";
$data = mysqli_query($conn, $query);
$json_array = array();
while($row = mysqli_fetch_array($data)){
array_push($json_array, array(
"success" => true,
"cnrp" => $row["cnrp"],
"area" => $row["area"],
"kondisi" => $row["kondisi"],
));
}
echo json_encode($json_array);
我这样的结果
[
{
"success": true,
"cnrp": "1",
"area": "Administrator",
"kondisi": "Sehat"
},
{
"success": true,
"cnrp": "2",
"area": "AMK CPBP",
"kondisi": "Sehat"
},..
]
是的,我知道这是一个古老的问题,有许多类似的问题。但是我一点都不知道。感谢您的帮助。谢谢。
答案 0 :(得分:0)
如果要将不同的json类型转换为单个json,可以先拆分查询,然后执行每个查询。为了得到这样的嵌套对象结果
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
尝试执行
while($row = mysqli_fetch_assoc($data)){
$json_arr['counter'][$row['a']] = $row['b'];
}
用于嵌套数组
"bar_months":[
"jan",
"feb",
"mar"
]
使用此
while($row = mysqli_fetch_assoc($data)){
$json_arr2['bar_months'][] = $row_area['months'];
}
并将其合并为单个json您可以使用
echo json_encode(array_merge($json_arr, $json_arr2));
希望它会有所帮助