

Calculate the array of values in PHP
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.

Calculate the array of values in PHP
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;
}
Recommend
-
7
Find values in an array with duplicate values advertisements I have an array of customer names. This array is full of duplicates, and needs to be...
-
13
jQuery: Calculate Sum Of all Textbox Values In a Table Column Satinder Singh / June 20, 2021 /
-
12
PHP: grouping the values of the array by the keys advertisements I have three array like this:
-
16
How to count all elements or values in an array in PHP 1701 views 2 years ago PHP Use the PHP count()
-
8
How to remove empty values from an array in PHP 1358 views 2 years ago PHP Use the PHP array_filter()
-
1
Calculate the Median of an Array in JavaScript Aug 24, 2022 To calculate the median of an array in JavaScript, perform the following steps: Make sure there are elements in the array.
-
11
How to sort an array values alphabetically in PHP 3326 views 2 years ago PHP Use the PHP sort() a...
-
5
How to remove duplicate values from an array in PHP 1359 views 2 years ago PHP Use the PHP array_unique(...
-
9
SAP Support 27 minutes ago How to automatically calculate the values of activities when posting confirmation via API?
-
11
This tutorial will discuss about unique ways to check if array contains all values from another array in php. Table Of Contents Method 1: Using array_diff() function ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK