php - 如何组合 3 个数组

标签 php mysql arrays json

社区您好

我只是想问一下我的代码。我只想结合我的 3 个变量

$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);

使用此代码可以正常工作。有2个变量。我希望它通过树变量来完成

$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);

这是我的预期输出

{ 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}

最佳答案

$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);

关于php - 如何组合 3 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55709359/

相关文章:

php - 如何通过联合来区分查询

php - 如何从 Javascript 执行外部 php?

c - 如何将数组作为地址发送到函数

ios - 如何在使用 AVPlayer 播放视频之前检测 AirPlay 是否处于事件状态?

php - JavaScript setInterval() 不显示内容?

php - 从 mySQL 数组中的 php 函数返回变量

php - 如何在mysql中插入多维数组?

MySQL Order By 不使用 ASC 或 DESC

c - 结构指针数组 - 覆盖结构

php - jquery .eq 不适用于某些导航项目