Search code examples
phparrayssortingranking

php sort array and rank specific field


I am trying to output a ranking by lowest number first for a particular field (OurPrice) based on numeric values.

var_dump Result

$myarray = array_filter($rankresult);
natsort($myarray); 

array(6) { 
    ["Comp7"]=> string(3) "189" 
    ["OurPrice"]=> string(3) "189" 
    ["Comp9"]=> string(6) "198.99" 
    ["Comp6"]=> string(3) "208" 
    ["Comp3"]=> string(6) "226.97" 
    ["Comp4"]=> string(3) "274" 
} 

You will notice that there are 6 total in the count and two of which are the same number, therefore it would equal the same rank (ie. Comp7 and OurPrice are both ranked 1 of 6).

Desired Output:

Our Price Rank = 1 of 6


Solution

  • try with this code

     $newarray = (array_unique(array_values($myarray)));
     $rank = array_search($myarray['OurPrice'],$newarray)+1;
     $count = count($myarray));
     echo "Our Price Rank" . $rank . " of " . $count"