我有一个数组,用于存储一个人在几个不同科目中的分数,例如:
$scores = array(
'reading' => 80,
'math' => 85,
'science' => 75,
'social studies'=> 90,
'music' => 95);
我需要以字符串形式获取前 3 个主题(键)的列表:
$topScores = "Music, Social Studies, Math";
什么是干净有效的方法来做到这一点?
最佳答案
以相反的顺序对数组进行排序,并与 arsort() 保持关联。然后取出数组的一部分(前三个元素)。
arsort( $scores );
$topScores = array_slice( $scores, 0, 3 );
然后,您可以使用 implode 从切片数组生成字符串。
Rizier123 指出您想要字符串中的键,因此您需要对键进行内爆。类似的东西
$topScoresStr = implode( ', ', array_keys( $topScores ) );
关于php - 如何在 PHP 中获取关联数组中的前 n 个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048038/