Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

arrays - rank in php based on average values

I've been trying for a while but still, I'm stuck here. Actually I need to get rank from average values. Here my result

Average         Rank
   39        39 rank is 1
   32        32 rank is 1
   51        51 rank is 1
   57        57 rank is 1

what I really need is

Average           Rank
  39               3 
  32               4 
  51               2 
  57               1

I've tried several method, but nothing seem to be works. Btw Here's my code

<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?> 

<?php 
$array = array($avg);
$i=1;
foreach($array as $key=>$value) 
{
    $max = max($array);
    echo "
".$max." rank is ". $i."
";
    $keys = array_search($max, $array);    
    unset($array[$keys]);
    if(sizeof($array) >0)
    if(!in_array($max,$array))
        $i++;
}
					
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?> 

<?php 
$array = array($avg); // useless
$i=1;
foreach($array as $key=>$value)  // also useless, you never use these variables, and since $array contains only one entry, there is no need to foreach it
{
    $max = max($array);
    echo "
".$max." rank is ". $i."
";
    $keys = array_search($max, $array);    
    unset($array[$keys]);
    if(sizeof($array) >0)
    if(!in_array($max,$array))
        $i++;
}

Let's clean that up :

<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?> 

<?php 
$max = $avg; // That's actually what you were doing. Cleaning the code makes it obvious, that's all
echo "
".$max." rank is ". $i."
";
$keys = array_search($max, $array);    
unset($array[$keys]);
if(sizeof($array) >0)
if(!in_array($max,$array))
    $i++;
}

The code still has errors, but the more we correct, the more its design flaws appear, and the less it's therefore correctable. You should, in my opinion, look at that code, figure a way to put all the values you want to have in $array in it so that then you can compute the datas you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...