Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中获得关联数组中的前n个键?_Php_Arrays_Sorting_Associative Array - Fatal编程技术网

如何在PHP中获得关联数组中的前n个键?

如何在PHP中获得关联数组中的前n个键?,php,arrays,sorting,associative-array,Php,Arrays,Sorting,Associative Array,我有一个数组,用于存储多个不同科目的个人分数,例如: $scores = array( 'reading' => 80, 'math' => 85, 'science' => 75, 'social studies'=> 90, 'music' => 95); 我需要以字符串形式获取前3个主题(键)的列表: $topScores = "Music, Social Studies, Math"; 什么是一种干净有效的方

我有一个数组,用于存储多个不同科目的个人分数,例如:

$scores = array(
    'reading' => 80,
    'math' => 85, 
    'science' => 75, 
    'social studies'=> 90, 
    'music' => 95);
我需要以字符串形式获取前3个主题(键)的列表:

$topScores = "Music, Social Studies, Math";

什么是一种干净有效的方法?

以相反的顺序对数组进行排序,并保持与arsort()的关联。然后取数组的一部分(前三个元素)

然后可以使用内爆从切片数组生成字符串


Rizier123指出,您需要字符串中的键,因此需要对键进行内爆。差不多

$topScoresStr = implode( ', ', array_keys( $topScores ) );

按与arsort()保持关联的相反顺序对数组排序。然后取数组的一部分(前三个元素)

然后可以使用内爆从切片数组生成字符串


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;

这是我带来的东西:

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);

以下是我提出的解决方案:

$sorted = $scores;
arsort($sorted);
$top_three = array_slice(array_keys($sorted), 0, 3);
$skills = implode(', ',$top_three);
$this->top_skills = ucwords($skills);

对数组进行排序,获取数组的键,然后是前3个。对数组进行排序,获取数组的键,然后是前3个。与单行程序不太一样:1)arsort返回bool;)2) OP想要keys@Rizier123,是的,我只是查了一下以验证它是否是引用。
$scores=array_slices(…)
@fusion3k:好吧,你扭伤了我的手臂,我会把作业放进去:PDOES不太像一行程序:1)arsort返回bool;)2) OP想要keys@Rizier123,是的,我只是查了一下以验证它是否是一个引用。
$scores=array\u slices(…)
@fusion3k:好的,你扭伤了我的手臂,我会把作业放进去:PImplode比循环更好,如果他们真的希望单词大写,他们可以用ucwords调用array\u过滤器。ucfirst不适用于“社会研究”。在这方面,内爆比循环更好,如果他们确实希望单词大写,他们可以使用ucwords调用array_filter。ucfirst不适合“社会研究”。