【问题标题】:How to Combine 3 Arrays如何组合 3 个数组
【发布时间】:2019-04-16 13:28:10
【问题描述】:

你好社区

我只是想问一下我的代码。我只想结合我的 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}

【问题讨论】:

  • 目前还不清楚您到底想要实现什么。请发布输入和预期输出以及错误/问题
  • Array combine 将 2 个数组合并为一个键值对。在这种情况下你真的不需要使用。你想创建一个 JSON 字符串 3 个或更多键吗?
  • 我已经在上面添加了我的预期输出,谢谢
  • 我只想合并我的 3 个数组

标签: php mysql arrays json


【解决方案1】:
$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);

【讨论】:

    【解决方案2】:

    不需要使用多个数组,多维数组就可以得到想要的结果。

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

    【讨论】:

    • 上面的代码是一个例子,你必须用这种方式弄清楚
    • 是的,我同意我为数组变量使用了适当的名称,我应该更改它
    • @B001ᛦ 好吧,我猜提问者会明白这一点,我应该给出完整的例子:)。
    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2016-08-30
    • 1970-01-01
    • 2019-06-24
    • 2013-08-28
    相关资源
    最近更新 更多