Ranking with PHP under certain conditions
I have grades taken by several students in a php array.
$ firstarray:
Array (
[0] => Array (
[6] => Array ( //I want to skip this student from ranking
[ENGLISH] => 45.00
[MATHEMATICS] => 5.00
[SCIENCE] => 40.00
)
)
[1] => Array (
[7] => Array (
[ENGLISH] => 41.00
[MATHEMATICS] => 40.00
[SCIENCE] => 47.00
)
)
)
[2] => Array (
[8] => Array (
[ENGLISH] => 42.00
[MATHEMATICS] => 44.00
[SCIENCE] => 40.00
)
)
[3] => Array (
[9] => Array (
[ENGLISH] => 42.00
[MATHEMATICS] => 25.00
[SCIENCE] => 31.00
)
)
)
In another array, I have the total grade scored by each student with a ranking .:
$ secondarray:
Array ( [7] =>
Array (
[score] => 128
[rank] => 1
)
[8] =>
Array (
[score] => 126
[rank] => 2
)
[9] =>
Array (
[score] => 98
[rank] => 3
)
[6] =>
Array (
[score] => 90
[rank] => 4
)
)
After subtracting the final grade of the students for all subjects, I used the following php code to calculate the rankings with links:
$ totalmarkscore:
Array (
[0] => Array (
[6] => 90
)
[1] => Array (
[7] => 128
)
[2] => Array (
[8] => 126
)
[3] => Array (
[9] => 98
)
)
$rankchu =array();
foreach($totalmarkscore as $k => $vl){
if(is_array($vl)){
foreach($vl as $hlutna =>$ken){
$rankchu[$hlutna]= $ken;
}
}
}
$secondarray = setRankings($rankchu);
My question is, how do I skip calculating the rank of a student who does not receive a minimum of 15 points from each subject? But I still want to show the details of the student grade, I just want to skip it from the ranking and then keep the ranking order. In the example above, I want to skip the student with id = 6 because he did not get at least 15 points (he only got 5 points) in math based on ranking, the rest remained the same. Please help. Thank.
source to share
When you process $firstarray
, you need to store information about whether any of the scores were less than 15. Here we add a flag can_be_scored
to store this:
$totalmarkscore = array_reduce(
$firstarray,
function($result, $item) {
$id = key($item);
$scores = $item[$id];
$result[$id] = array(
"score" => array_sum($scores),
"can_be_scored" => min($scores) >= 15
);
return $result;
},
array()
);
It $totalmarkscore
should look something like this:
Array (
[7] =>
Array (
[score] => 128
[can_be_scored] => true
)
[8] =>
Array (
[score] => 126
[can_be_scored] => true
)
[9] =>
Array (
[score] => 98
[can_be_scored] => true
)
[6] =>
Array (
[score] => 90
[can_be_scored] => false
)
)
Then in, setRankings
you can check if $item["can_be_scored"]
and exclude the element if it is false.
source to share