对 php 数组进行排序,获取某个数字在其他数组中出现的次数

Sort a php array getting the times a number appears in other array

我正在尝试使用来自数据库 $user_rating_points 的数组来获得用户收到的有序分数列表以及他收到每个分数的次数。基本得分值定义为可能得分的数组 $score_points.

假设对用户的查询为他的给定点提供了以下数组:

    // The base score points' scale
    $score_points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // The array of points a user received (from the database query)
    $user_rating_points = [1, 3, 2, 7, 3, 4, 9, 2, 10, 6, 1, 7, 10, 8, 4, 8, 9, 4, 7, 10, 5];

我想实现如下目标:

我已经尝试将 array_count_values($user_rating_points)sort($user_rating_points); 一起使用,但是在 HTML ul 或 print_r($user_rating_points) 上我无法获得如上所示的列表例如。

在此先感谢您就此问题提供的任何帮助,解决起来可能比我预期的要简单得多,但我似乎陷入了一个循环,没有找到解决方案。

这是我的解决方案。 键排序为 1->10,没有 0。 如果您有出现 0 次的点,它们也会出现在结果中。

<?php
// The base score points' scale
$score_points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// The array of points a user received (from the database query)
$user_rating_points = [1, 3, 2, 7, 3, 4, 9, 2, 10, 6, 1, 7, 10, 8, 4, 8, 9, 4, 7, 10, 5];
$user_score = array_fill_keys($score_points, 0);
foreach (array_count_values($user_rating_points) as $k => $v) {
    $user_score[$k] = $v;
}
print_r($user_score);

?>

输出为

Array
(
    [1] => 2
    [2] => 2
    [3] => 2
    [4] => 3
    [5] => 1
    [6] => 1
    [7] => 3
    [8] => 2
    [9] => 2
    [10] => 3
)
$result = array_combine(
    $score_points,
    array_map(
        fn($score_point) => count(
            array_filter($user_rating_points, fn($value) => $value === $score_point)
        ),
        $score_points
    )
);