如何获取数组结果中的标签

How to get the label in the result of an array

以下代码按预期工作以获取每个年龄组的患者数量。

它也获得了最高(或最常见)的年龄组。

$count_0_19 = 0;
$count_20_29 = 0;
$count_30_39 = 0;
$count_40_49 = 0;
$count_50_59 = 0;
$count_above_60 = 0;
$curr_year = date('Y');

$sql= "SELECT pt_dob FROM ptlist WHERE mid=$userID";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $pdo->query($sql);

$pt_dob = $row[ 'pt_dob' ];

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$pt_dob = explode('-', $row['pt_dob']);
$year = $pt_dob[0];
$month = $pt_dob[1];
$day = $pt_dob
$temp = abs($curr_year - $year);

if($temp >= 0 && $temp <= 19) {
$count_0_19++;
  }
elseif($temp >= 20 && $temp <= 29) {
$count_20_29++;
  }
elseif($temp >= 30 && $temp <= 39) {
$count_30_39++;
  }
elseif($temp >= 40 && $temp <= 49) {
$count_40_49++;
  }
elseif($temp >= 50 && $temp <= 59) {
$count_50_59++;
  }
else {
$count_above_60++;
  }
}

echo '0-19: '.$count_0_19.'<br>';
echo '20-29: '.$count_20_29.'<br>';
echo '30-39: '.$count_30_39.'<br>';
echo '40-49: '.$count_40_49.'<br>';  // example output is > 40-49: 7 (i.e. 7 patients in age group 40-49)
echo '50-59: '.$count_50_59.'<br>';
echo '60+: '.$count_above_60.'<br>';

// getting highest value

$a = array($count_0_19, $count_20_29, $count_30_39, $count_40_49, $count_50_59, $count_above_60);

$res = 0;
    foreach($a as $v) {
        if($res < $v)
            $res = $v;
    }

echo $res;

^^ 这告诉我,例如9 名患者在 30-39 岁年龄组 - 即该年龄组患者人数最多。

但是 $res 只给我数字(例如 9)。

我要你帮忙的是让 $res 给我文本(或标签)“30-39”,而不是数字 9。

请帮忙。

您可以通过创建标签数组然后递增它来存档它,然后从 $label 数组中找到最大值以获得密钥。

$label = [
  "0_19" => 0,
  "20_29" => 0,
  "30_39" => 0,
  "40_49" => 0,
  "50_59" => 0,
  "above_60" => 0,
];

while ($row4 = $result4->fetch(PDO::FETCH_ASSOC)) {
  $pt_dob = explode('-', $row4['pt_dob']);
  $year = $pt_dob[0];
  $month = $pt_dob[1];
  $day = $pt_dob$temp = abs($curr_year - $year);
  if ($temp >= 0 && $temp <= 19) {
    $label['0_19'] = $label['0_19'] +1;
  }
  elseif ($temp >= 20 && $temp <= 29) {
    $label['20_29'] = $label['20_29'] +1;
  }
  elseif ($temp >= 30 && $temp <= 39) {
    $label['30_39'] = $label['30_39']+1;
  }
  elseif ($temp >= 40 && $temp <= 49) {
    $label['40_49'] = $label['40_49'] +1;
  }
  elseif ($temp >= 50 && $temp <= 59) {
    $label['50_59'] = $label['50_59']+1;
  }
  else {
    $label['above_60']= $label['above_60']+1;
  }
}


echo $maxs = array_keys($label, max($label));

echo "<br/>";


foreach($label as $k => $v);
    echo "key $k count $v <br/>";

从评论继续...您需要将 $key 存储到一个变量中。

$a = array('0-19'=>$count_0_19, '20-29'=>$count_20_29, '30-39'=>$count_30_39, '40-49'=>$count_40_49, '50-59'=>$count_50_59, '60+'=>$count_above_60); 
$res = 0; 
$label = '';
foreach($a as $key => $v) { 
    if($res < $v){
        $res = $v;
        $label = $key; //get label from key and store in a variable
    }
} 
echo 'label = '.$label . ' , Number = '.$res;