我有这样的数组结果
main() {
Function(String) onTextReady;
if(onTextReady != null) {
onTextReady('null');
}
Function(String) onTextReady2 = (s) => print(s);
if(onTextReady2 != null) {
onTextReady2('not null');
}
}
但是我想这样改变数组:
{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}}
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}
这是我在php中的控制器
data: [{NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"},…]
0: {NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"}
1: {NamaKecamatan: "BOJONGSARI", total: "20", laki: "7", cewe: "13"}
2: {NamaKecamatan: "CILODONG", total: "93", laki: "48", cewe: "45"}
3: {NamaKecamatan: "CIMANGGIS", total: "96", laki: "47", cewe: "49"}
4: {NamaKecamatan: "CINERE", total: "13", laki: "7", cewe: "6"}]
请帮助我更改此数据
答案 0 :(得分:1)
$data = '[{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}},
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}]';
$array_data = json_decode($data, ture);
$result = [];
foreach($array_data as $item) {
$result['data'][] = $item['data'];
}
return json_encode($result);
答案 1 :(得分:0)
您可以按照以下方式进行处理
public function countByKecamatan(){
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
$i = 0;
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
($i > 0) ? ($data[] = $row) : ($data = array('data' => $row));
$i++;
}
echo json_encode($data);
}
答案 2 :(得分:0)
您得到的输出归结为以下2个小问题...
$data = array(
"data" => $row,
);
echo json_encode($data);
首先,您正在使用要删除的额外级别构建阵列。然后,第二行代码一次回显每个数据。您需要建立所有记录的列表,然后一次性返回全部数据。
public function countByKecamatan(){
// Create empty array for data
$data = [];
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
// Add new row of data to data to be returned
$data[] = $row;
}
// Return all of the data in JSON format
return json_encode($data);
}
请注意,这将返回值而不是回显它-如果在调用控制器时,框架需要以其他方式(例如,作为Response对象的一部分)对其进行编码,则可能需要更改此值。