我有这个参数数组:
array[Tour Eiffel] = 0.6225
array[Arc de Triomphe] = 0.85
array[Avenue des Champs-Elysees] = 0.28
array[Place de la Concorde] = 0.3425
array[Palais Garnier] = 0.5025
array[Galeries Lafayette] = 0.35
array[Moulin Rouge] = 0.5425
array[Louvre] = 0.9425
array[Centre Pompidou] = 0.4425
array[Eglise Saint-Eustache] = 0.5825
我想按顺序找到前五个最大元素并打印结果如下:
Louvre is 0.9425
Arc de Triomphe is 0.85
Tour Eiffel is 0.6225
Eglise Saint-Eustache is 0.5825
Moulin Rouge is 0.5425
我使用了函数max()但这只返回了最大值而没有参数键(例如Louvre)。
答案 0 :(得分:1)
arsort($array); // sort array in reverse order
$top_vals = array_slice($array, 0, 5, true); // taking first 5 elements preserving keys
foreach ($top_vals as $k => $v)
echo $k . ' is ' . $v . '<br />';
答案 1 :(得分:0)
使用arsort以相反的顺序对数组进行排序并维护索引关联
arsort($arr, SORT_NUMERIC);
$count = 0;
foreach ($arr as $key => $val) {
echo "$key is $val";
$count += 1;
if ($count === 5) {
break;
}
echo '<br />';
}