从PHP的多维数组中获取前5个值



我有以下数组:

Array ( 
[0] => Array ( 
    [count] => 9 
    [user_id] => 2 
) 
[1] => Array ( 
    [count] => 25 
    [user_id] => 1 
) 
[2] => Array ( 
    [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 
))

这只是一个样品。实际的数组将包含更多的子数组。

我需要能够从"count"中获得前五个值,并将它们与其关联的"user_id"存储。

最终的结果应该是这样的:

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 
) )

如果这可以通过简单地重新排序数组来完成,那就可以了。

谢谢!

您要找的是usortarray_slice

例子:

<?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);

输出:

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);

相关内容

  • 没有找到相关文章

最新更新