开发者

Get top 5 values from multidimensional array in PHP [duplicate]

开发者 https://www.devze.com 2023-03-21 01:27 出处:网络
This question already has answers here: How to sort an array of arrays in php? (3 answers) php - usort or array_multisort?
This question already has answers here: How to sort an array of arrays in php? (3 answers) php - usort or array_multisort? (3 answers) Get the first N elements of an array? (5 answers) PHP: Any function that return first/last N elements of an array (2 answers) Closed 3 years ago.

I have the following array:

Array ( 
[0] => Array ( 
    [count] => 9 
    [user_id] => 2 
) 
[1] => Array ( 
    [count] => 25 
    [user_id] => 1 
) 
[2] => Array ( 
  开发者_JS百科  [count] => 20 
    [user_id] => 3 ) 
[3] => Array ( 
    [count] => 6 
    [user_id] => 56 ) 
[4] => Array ( 
    [count] => 2 
    [user_id] => 37 ) 
[5] => Array ( 
    [count] => 1 
    [user_id] => 0 
))

This is just a sample. The actual array will contain many more sub arrays.

I need to be able to obtain the top five values from "count" and store them with their associated "user_id".

The final result needs to look something like this:

Array ( 
[0] => Array ( 
    [count] => 25 
    [user_id] => 1 
) 
[1] => Array ( 
    [count] => 20 
    [user_id] => 3
) 
[2] => Array ( 
    [count] => 9 
    [user_id] => 2 
)   
[3] => Array ( 
    [count] => 6 
    [user_id] => 56 
)  
[4] => Array ( 
    [count] => 2 
    [user_id] => 37 
) 
[5] => Array ( 
    [count] => 1 
    [user_id] => 0 
) )

If this can be done by simply re ordering the array, that is fine.

Thanks!


You're looking for usort and array_slice.

Example:

<?php

$array = array(
  array(
    'count' => 9,
    'user_id' => 2
  ),
  array(
    'count' => 25,
    'user_id' => 1
  ),
  array(
    'count' => 20,
    'user_id' => 3
  ),
  array(
    'count' => 6,
    'user_id' => 56
  ),
  array(
    'count' => 2,
    'user_id' => 37
  ),
  array(
    'count' => 1,
    'user_id' => 0
  )
);

function usort_callback($a, $b)
{
  if ( $a['count'] == $b['count'] )
    return 0;

  return ( $a['count'] > $b['count'] ) ? -1 : 1;
}

usort($array, 'usort_callback');

$top5 = array_slice($array, 0, 5);

print_r($top5);

Outputs:

Array
(
    [0] => Array
        (
            [count] => 25
            [user_id] => 1
        )

    [1] => Array
        (
            [count] => 20
            [user_id] => 3
        )

    [2] => Array
        (
            [count] => 9
            [user_id] => 2
        )

    [3] => Array
        (
            [count] => 6
            [user_id] => 56
        )

    [4] => Array
        (
            [count] => 2
            [user_id] => 37
        )

)


usort($array, function ($a, $b) { return $b['count'] - $a['count']; });
$top5 = array_slice($array, 0, 5);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号