【问题标题】:php sort array and rank specific fieldphp排序数组并对特定字段进行排名
【发布时间】:2012-05-09 16:56:31
【问题描述】:

我正在尝试根据数值首先为特定字段 (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 都在 6 中排名第 1)。

期望的输出:

我们的价格排名 = 1 of 6

【问题讨论】:

  • 我不知道从这里去哪里。难道没有办法获取“OurPrice”的Rank顺序吗?
  • @ToddN:输出应该如何,只是Our Price Rank = 1 of 6
  • 是的,所以基本上我会使用echo "Our Price Rank" . $rank . " of " . $count"; 类似的东西。

标签: php arrays sorting ranking


【解决方案1】:

试试这段代码

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

【讨论】:

  • 与我的回答类似,鉴于我在问题中的初始数据,我喜欢这种方法。乔纳森的帖子提到的重点是array_search。
【解决方案2】:

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

$keys = array_keys( $array );
$rank = array_search( "OurPrice", $keys );

printf( "We rank %d of %d", ++$rank, count($keys) );

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2020-08-09
    • 2019-11-04
    • 1970-01-01
    • 2012-11-15
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多