PHP 对数组进行排序并排名特定字段


php sort array and rank specific field

我正在尝试根据数值首先输出特定字段(OurPrice)的最低数字排名。

var_dump结果

$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" 
} 

您会注意到计数中总共有 6 个,其中两个是相同的数字,因此它将等于相同的排名(即。Comp7 和 OurPrice 均排名 1/6)。

期望输出:

我们的价格等级 = 1 of 6

尝试使用此代码

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

假设您已经对值进行了排序(看起来您已经排序了),您可以简单地告诉它们"OurProduct"键所在的索引。

$keys = array_keys( $array );
$rank = array_search( "OurPrice", $keys );
printf( "We rank %d of %d", ++$rank, count($keys) );

在线试用:http://codepad.org/qIwTGBzG