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

时间:2011-07-15 15:58:36

标签: php sorting multidimensional-array max

我有以下数组:

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

如果只需重新排序数组即可完成,那很好。

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在寻找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
        )

)

答案 1 :(得分:1)

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