8

Calculate the array of values ​​in PHP

 3 years ago
source link: https://www.codesd.com/item/calculate-the-array-of-values-in-php.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Calculate the array of values ​​in PHP

advertisements

I have an array i.e.

Array
(
    [18] => 0.6667
    [228] => 0.3333
    [25] => 0.3333
    [568] => 0.3333
    [762] => 0
    [740] => 0
    [742] => 0
)

I want to rank them as

Array
(
    [18] => 0.6667  //1
    [228] => 0.3333 //2
    [25] => 0.3333  //2
    [568] => 0.3333  //2
    [762] => 0       //3
    [740] => 0       //3
    [742] => 0       //3
)

I have tried using following code:

arsort($rank);
foreach ($rank as $k => $v) {
        $i=1;
        foreach ($rank as $k1 => $v1) {
            if($v==$v1){
                $newrank[$k]=$i;
            }
            else{
                $i++;
            }
        }
    }

But it gives me result

Array
(
    [18] => 0.6667  //1
    [228] => 0.3333 //2
    [25] => 0.3333  //2
    [568] => 0.3333  //2
    [762] => 0       //5
    [740] => 0       //5
    [742] => 0       //5
)

I am unable to rectify why rank is increasing from 2 to 5.

Please help.


You don't need nested loops. Just iterate through the array, and increment $i whenever the score changes.

$newrank = array();
$i = 0;
$last_v = null;
foreach ($rank as $k => $v) {
    if ($v != $last_v) {
        $i++;
        $last_v = $v;
    }
    $newrank[$k] = $i;
}

Tags php

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK