The following code works as expected to get the number of patients per age group.
It also gets the highest (or most common) age group.
$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;
^^ This tells me that e.g. 9 patients are in the 30-39 age group - i.e. the highest number of patients are in this age group.
But $res gives me only the number (e.g. 9).
What I am asking your help with is to get $res to give me the text(or label) "30-39", instead of the number 9.
Please help.
continue from comment... you need to store $key into a variable.
$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;
You can archived this by creating the array of labels and then incrementing it according and then find the greatest value form the $label array to get the key.
$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/>";
Related
i have time slots like
$timeslot = ['09:00-10:00', .... '23:00-00:00', '00:00-01:00'];
I have records with updated time as 23:15:00, 23:30:00, 00:15:00, 09:15:00 etc.
What i'm trying to find is the sum of records between each of the $timeslot. I'm not considering what day got updated, only time i'm looking for.
i tried with:-
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
foreach($data as $val) {
$cnt = 0;
foreach($timeslot as $slots) {
$slot = explode("-", $slots);
if( (strtotime($val) > strtotime($slot[0])) && (strtotime($val) <= strtotime($slot[1])) ) {
$up_time[$slot[0] . '-' . $slot[1]] = $cnt++;
}
}
}
echo '<pre>';print_r($up_time);echo '</pre>';
The expected output is:-
09:00-10:00 = 1
23:00-00:00 = 2
00:00-01:00 = 1
Strtotime is not required since your time can be compared as strings.
This code works as you expected.
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
$timeslot = ['09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
if (!isset($up_time[$slot])) {
$up_time[$slot] = 1;
} else {
$up_time[$slot]++;
}
}
}
}
echo '<pre>';
print_r($up_time);
echo '</pre>';
The if with 'substr' is needed because for midnight you have '00' and not '24' so the computer thinks is an empty set (such as hours bigger then 23 and smaller then 0).
Comparison is made between string because bigger time is also a bigger string since you use 2 digits for hours.
You need to count equal slots so you need an array with an element for each slot and increment if duplicate or create an element if not found (the condition '!isset').
Update for modification request
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
// added unused slot 8:00-9:00
$timeslot = ['08:00-09:00','09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
// new initialization
foreach ($timeslot as $slot) {
$up_time[$slot] = 0;
}
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
$up_time[$slot]++; // simplified
}
}
}
I would appreciate some guidance on the following issue. I am by no means an expert in php. The code below takes almost 10 seconds to execute! Is there anything I am doing that is wrong or bad practice?
$data = [];
$today = date("Y/m/d");
$ThisYear = Date('Y'); //get current Year
$ThisMonth = Date('m'); //get current month
$Tday = '01'; //first day of month
$Tmonth = '09'; //September
if (8 < $ThisMonth && $ThisMonth < 13) {
$AcYear = $ThisYear; }
else {
$AcYear = $ThisYear - 1; // sets start of academic year to be last year
}
$AcFullYear = $AcYear.'/'.$Tmonth.'/'.$Tday;
//find rank in all school
$students_rank = [];
$school_id = Student::model()->findByAttributes(['user_master_id' => Yii::app()->user->id])->school_master_id;
$criteria1 = new CDbCriteria;
$criteria1->with = array('user');
$criteria1->condition = "t.school_master_id=:school_master AND user.status ='1'";
$criteria1->params = array(':school_master' => $school_id);
$school_students_details = Student::model()->findAll($criteria1);
foreach ($school_students_details as $key => $value) {
$student_name = StudentDetails::model()->findByAttributes(['user_master_id' => $value->user_master_id]); //student details with year group
$criteria2 = new CDbCriteria;
$criteria2->with = array('homeworkMaster');
$criteria2->condition = "t.student_id=:student_id AND homeworkMaster.question_type_id<>:question_type_id";
$criteria2->params = array(':student_id' => $value->user_master_id, ':question_type_id' => 6);
$HW_assignment_track = HomeworkAssignmentTrack::model()->findAll($criteria2);
$total_HW = count((array)$HW_assignment_track);
$student_score = 0;
$student_rank = 0;
$student_total_score = 0;
$total_HW_marks = 0;
$under_deadline_HW = 0;
$criteria3 = new CDbCriteria();
$criteria3->condition = "student_id =:student_id AND status=:status AND created_at >= '$AcFullYear' AND created_at <= '$today'";
$criteria3->params = [':student_id' => $value->user_master_id, ':status' => 2];
$student_completed_HW = HomeworkStudentAnswere::model()->findAll($criteria3);
$i = 1;
foreach ($student_completed_HW as $s_c_h_K => $s_c_h_V) {
if ($s_c_h_V->homework->homework_type == 2) {
$total_HW -= 1;
} elseif ($s_c_h_V->homework->homework_type == 1) {
$HW_questions = HomeworkQuestion::model()->findAllByAttributes(['homework_master_id' => $s_c_h_V->homework_id, 'status' => 1]);
foreach ($HW_questions as $qKey => $qVal) {
if ($qVal->question_type_id ==3) {
$total_HW_marks += 2;
} else {
$total_HW_marks += $qVal->marks;
}
}
$assignment = HomeworkAssignmentTrack::model()->findByAttributes(['id' => $s_c_h_V->assignment_track_id]);
$homeworks_within_validate = Assignment::model()->findByPk($assignment->assignment_id);
if ($homeworks_within_validate->valid_date === '0' && $homeworks_within_validate->deadline >= date('Y-m-d')) {
$total_HW -= 1;
}
if ($homeworks_within_validate->valid_date === '1' || (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($s_c_h_V->created_at))) && ($homeworks_within_validate->deadline < date('Y-m-d')))) {
if ($s_c_h_V->review_status === '2') {
$student_total_score += $s_c_h_V->score;
}
}
$homework_submit = HomeworkCompleteNotification::model()->findByAttributes(['homework_id' => $s_c_h_V->homework_id, 'assignment_track_id' => $s_c_h_V->assignment_track_id, 'student_id' => $value->user_master_id]);
if (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($homework_submit->created_at))) && ($s_c_h_V->review_status === '2')) {
$under_deadline_HW += 10;
}
if ($total_HW_marks !=0) {
$student_score += round(($student_total_score / $total_HW_marks) * 100);
} else {
$student_score = 0;
}
}
$i += 1;
}
//add revision scores to rank score
$criteria4 = new CDbCriteria();
$criteria4->condition = "user_id =:user_id AND date_created >= '$AcFullYear' AND date_created <= '$today'";
$criteria4->params = [':user_id' => $value->user_master_id];
$revision_score = RevisionScores::model()->findAll($criteria4);
$sum = 0;
foreach($revision_score as $item) {
$sum += $item['score'];
} //end of adding revision scores
$students_rank[$key]['student_id'] = $value->user_master_id;
$students_rank[$key]['year_group'] = $student_name->year_group_id; //added year group to model array
if ($student_score > 0) {
$student_rank += round($student_score / $total_HW, 0) + $under_deadline_HW;
$students_rank[$key]['rank'] = $student_rank + $sum;
} else {
$students_rank[$key]['rank'] = $sum;
}
}
$model = $this->multid_sort($students_rank, 'rank');
$rank_score = round(array_column($model, 'rank', 'student_id')[Yii::app()->user->id],0);
$year_rank =[];
$current_st = StudentDetails::model()->findByAttributes(['user_master_id' => Yii::app()->user->id]);
$current_st_year = $current_st->year_group_id;
$rank_list = [];
foreach ($model as $key => $value) {
$rank_list[] = $value['student_id'];
if ($value['year_group'] == $current_st_year) {
$year_rank[] = $value['student_id'];
}
}
$user = Yii::app()->user->id;
$sch_position = array_search($user,$rank_list);
$yr_position = array_search($user,$year_rank);
$final_rank = $sch_position + 1;
$yr_rank = $yr_position + 1;
$sch_rank = $final_rank;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($sch_rank %100) >= 11 && ($sch_rank%100) <= 13) {
$sc_abbreviation = 'th';
$yr_abbreviation = 'th';
} else {
$sc_abbreviation = $ends[$sch_rank % 10];
$yr_abbreviation = $ends[$yr_rank % 10];
}
$models = UserMaster::model()->findByPk(Yii::app()->user->id);
$year_name = $models->studentDetails->yearGroup->name;
$data['type'] = 'success';
$data['score'] = '<div>Ranking Score: '.$rank_score.'</div>';
$data['yr_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$yr_rank. '</span><sup class="script-top" id="year_rank_abb">' .$yr_abbreviation. '</sup></div><div id="year_name">In ' .$year_name. '</div>';
$data['school_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$sch_rank. '</span><sup class="script-top" id="year_rank_abb">' .$sc_abbreviation. '</sup></div><div id="year_name">In School</div>';
$data['rank_revise'] ='<div>'.$rank_score.'</div>';
$data['yr_rank_revise'] = '<span>'.$yr_rank.'</span><sup class="superscript" style="left:0">'.$yr_abbreviation.'</sup>';
$data['sch_rank_revise'] = '<span>'.$sch_rank.'</span><sup class="superscript" style="left:0">'.$sc_abbreviation.'</sup>';
$_SESSION['rank'] = $rank_score;
$_SESSION['accuracy'] = $rank_score;
echo json_encode($data);
exit;
The above is used in an Yii application. It runs perfectly fine on localhost, but on live site, takes over 10 seconds to execute.
Your help and guidance is appreciated.
Thank
I have trouble to increment correctly a variable in a while loop where I fetch data from my database.
This is the code:
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//January
if ($row['month'] ==1){
if ($row['day_range'] == '01-07') {
$val1_1 = $row['duration'];
$int1_1 = $row['intensity'];
}
elseif ($row['day_range'] == '08-14') {
$val1_2 = $row['duration'];
$int1_2 = $row['intensity'];
}
elseif ($row['day_range'] == '15-21') {
$val1_3 = $row['duration'];
$int1_3 = $row['intensity'];
}
elseif ($row['day_range'] == '22-end') {
$val1_4 = $row['duration'];
$int1_4 = $row['intensity'];
}
//Avg intensity
$int1 = ($int1_1 + $int1_2 + $int1_3 + $int1_4)/4;
}
}
So I have this code for every month.
The problem here is that sometimes I don't have 4 values, so at the end when I calculate the AVG it is sometimes wrong because it always divides it by 4
What I've done :
I had the idea of incrementing a variable $i each time I have a value, like this
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//January
if ($row['month'] ==1) {
if ($row['day_range'] == '01-07') {
$val1_1 = $row['duration'];
$int1_1 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '08-14') {
$val1_2 = $row['duration'];
$int1_2 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '15-21') {
$val1_3 = $row['duration'];
$int1_3 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '22-end') {
$val1_4 = $row['duration'];
$int1_4 = $row['intensity'];
$i++;
}
//Avg intensity
$int1 = ($int1_1 + $int1_2 + $int1_3 + $int1_4)/$i;
}
$i = 0;
//code for next month
}
But it doesn't work, I've echoed it and $i stays at 1.
I think it is because it fetch row by row so it never goes through all incrementations to reach the value desired.
How can I do that please?
// Here is an array to get the data of EACH month
$month = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// This way, you will have $month[1] for January, $month[2] for February, etc.
$month[$row['month']][] = array(
"duration" => $row['duration'],
"intensity" => $row['intensity'];
);
}
// Now you get all the data, you can calculate the Avg intensity for each month
foreach ($month as $month_number => $data) {
$moy = count($month[$month_number]); // Will be 4 if you have 4 period, 3 if only 3, etc.
$sum = 0;
foreach ($data as $value) {
$sum += $value['intensity'];
}
$month[$month_number]['avg_intensity'] = $sum / $moy;
}
With this method you should get an array with all the data you want that look like this :
$month = array(
// January
1 => array(
0 => array(
'duration' => ...,
'intensity' => ...
),
1 => array(
'duration' => ...,
'intensity' => ...
),
...
'avg_intensity' => /* moy of all intensity of the month */
),
// February
2 => array(
...
),
...
);
Hope it helps you !
EDIT :
As suggested if the comment by Nigel Ren, you can replace
$sum = 0;
foreach ($data as $value) {
$sum += $value['intensity'];
}
By
$sum = array_sum(array_column($data, "intensity"));
Please try like
$int1_1 += $row['intensity'];
way.
That means
$i = 0;
$int1_1 = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//January
if($row['month'] ==1){
if($row['day_range'] == '01-07'){
$val1_1 = $row['duration'];
$int1_1 += $row['intensity'];
$i++;
}
elseif($row['day_range'] == '08-14'){
$val1_2 = $row['duration'];
$int1_1 += $row['intensity'];
$i++;
}
elseif($row['day_range'] == '15-21'){
$val1_3 = $row['duration'];
$int1_1 += = $row['intensity'];
$i++;
}
elseif($row['day_range'] == '22-end'){
$val1_4 = $row['duration'];
$int1_1 += $row['intensity'];
$i++;
}
//Avg intensity
$int1 = $int1_1/$i;
}
$i=0;
//code for next month
}
I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.
I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912