Reputation:
Hello Community
I just want to ask about my code. i just want to combine my 3 variable
$result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS `totalF` FROM mdr where disease = '$diseaseselection' GROUP BY disease , age");
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$tabx[]=$row['age'];
$taby[]=$row['totalM'];
$tabz[]=$row['totalF'];
}
$tableau=array_combine($tabx,$taby,$tabz);
foreach($tableau as $key=>$value){
$string[]=array('age'=>$key,'totalM'=>$value,'totalF'=>$value);
}
echo json_encode($string);
It works fine with this code. with 2 variable. and i want it to be done by tree variable
$result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS `totalF` FROM mdr where disease = '$diseaseselection' GROUP BY disease , age");
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$tabx[]=$row['age'];
$taby[]=$row['totalM'];
}
$tableau=array_combine($tabx,$taby);
foreach($tableau as $key=>$value){
$string[]=array('age'=>$key,'totalM'=>$value);
}
echo json_encode($string);
Here is my EXPECTED output
{ age:'0-1', totalM:2, totalF:1},
{ age:'1-4', totalM:1, totalF:0},
{ age:'10-14', totalM:0, totalF:1},
{ age:'15-19', totalM:0, totalF:1},
{ age:'5-9', totalM:0, totalF:3},
{ age:'55-59', totalM:6, totalF:0}
Upvotes: 0
Views: 58
Reputation: 286
There is no need to use multiple array, you can get desired result with multi dimensional array.
$key = 0;
$output = [];
while($row = mysqli_fetch_array($result)){
$output[$key]['age'] = $row['age'];
$output[$key]['totalM'] = $row['totalM'];
$output[$key]['totalF'] = $row['totalF'];
$key++;
}
echo json_encode($output);
Upvotes: 0
Reputation: 3870
$result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS `totalF` FROM mdr where disease = '$diseaseselection' GROUP BY disease , age");
$chart_data = '';
$data = [];
while($row = mysqli_fetch_array($result)) {
$data[] = [
'age' => $row['age'],
'totalM' => $row['totalM'],
'totalF' => $row['totalF']
];
}
echo json_encode($data);
Upvotes: 1