Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I’m trying to achieve a list of ordered score points a user received and the number of times he received each score using the array that comes from the database $user_rating_points. The base score values are defined as an array of possible points $score_points.

Imagining that the query for a user gives me the following array for his given 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];

I want to achieve something like the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 1 point: 3 times
  • 2 points: 2 times
  • 3 points: 5 times
  • 9 points: 2 times
  • 10 points: 3 times

I’ve tried using the array_count_values($user_rating_points) with sort($user_rating_points); but either on a HTML ul or a print_r($user_rating_points) I’m unable to get a list like the above example.

Thanks in advance for any help on this issue that is probably much simpler to solve than I expect, yet it seems like I’ve gone into a loop and not finding a solution.

>Solution :

Here is my solution.
Keys are sorted 1->10, no 0.
If you have points which appear 0 times, they will also be present in the results.

<?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(1, 10, 0);
    foreach (array_count_values($user_rating_points) as $k => $v) {
        $user_score[$k] = $v;
    }
    print_r($user_score);
?>

And the output is

Array
(
    [1] => 2
    [2] => 2
    [3] => 2
    [4] => 3
    [5] => 1
    [6] => 1
    [7] => 3
    [8] => 2
    [9] => 2
    [10] => 3
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading