Get top 5 values from multidimensional array in PHP [duplicate]
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);
精彩评论