Home > database >  Sort a php array getting the times a number appears in other array
Sort a php array getting the times a number appears in other array

Time:01-30

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:

  • 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.

CodePudding user response:

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_keys($score_points, 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
)

CodePudding user response:

$result = array_combine(
    $score_points,
    array_map(
        fn($score_point) => count(
            array_filter($user_rating_points, fn($value) => $value === $score_point)
        ),
        $score_points
    )
);

CodePudding user response:

   $user_rating_points = [1, 3, 2, 7, 3, 4, 9, 2, 10, 6, 1, 7, 10, 8, 4, 8, 9, 4, 7, 10, 5];
   $kval = array_count_values($user_rating_points);
   ksort($kval);
   $val=[];
   foreach($kval as $keys=>$x_value)
   {
     $val[$keys] = $x_value;
   }

   print_r($val); 
  

Your Output:-

     Array
       (
           [1] => 2
           [2] => 2
           [3] => 2
           [4] => 3
           [5] => 1
           [6] => 1
           [7] => 3
           [8] => 2
           [9] => 2
           [10] => 3
         )    
  •  Tags:  
  • Related