如何在 PHP 中获取关联数组中的前 n 个键?
How to get first n keys in associative array in PHP?
我有一个数组,用于存储一个人在几个不同科目中的分数,例如:
$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 ) );
这是我带来的东西:
arsort($scores);
$scores = array_slice($scores,0,3);
$finalString = null;
foreach($scores as $key => $value){
$finalString .= ucfirst($key).', ';
}
echo $finalString;
这是我想出的解决方案:
$sorted = $scores;
arsort($sorted);
$top_three = array_slice(array_keys($sorted), 0, 3);
$skills = implode(', ',$top_three);
$this->top_skills = ucwords($skills);
我有一个数组,用于存储一个人在几个不同科目中的分数,例如:
$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 ) );
这是我带来的东西:
arsort($scores);
$scores = array_slice($scores,0,3);
$finalString = null;
foreach($scores as $key => $value){
$finalString .= ucfirst($key).', ';
}
echo $finalString;
这是我想出的解决方案:
$sorted = $scores;
arsort($sorted);
$top_three = array_slice(array_keys($sorted), 0, 3);
$skills = implode(', ',$top_three);
$this->top_skills = ucwords($skills);