分割多维数组唯一值


PHP - Split multidimensional array unique values

我想如果我先解释一下会有帮助…我有一个比赛,每个县有3个获胜者(票数最高的那个)。

我的当前数组是这样的:

Array
(
    [0] => Array
        (
            [entryID] => 1
            [votes] => 3
            [countyID] => 46
        )
    [1] => Array
        (
            [entryID] => 4
            [votes] => 1
            [countyID] => 2
        )
    [2] => Array
        (
            [entryID] => 2
            [votes] => 0
            [countyID] => 46
        )
    [3] => Array
        (
            [entryID] => 5
            [votes] => 0
            [countyID] => 46
        )
)

这里我需要做的是找出在每个CountyID中找到前3名最高票数的方法。

有什么好主意吗?谢谢,斯科特。

最简单的方法是重新组织数组,使国家id成为顶级索引,然后编写一个简单的自定义函数按降序对投票计数进行排序…这样投票最多的条目就会排在最前面。

$entries = array(
    array('entryId' => 1, 'votes' => 3, 'countryId' => 46),
    array('entryId' => 4, 'votes' => 1, 'countryId' => 2),
    array('entryId' => 2, 'votes' => 0, 'countryId' => 46),
    array('entryId' => 5, 'votes' => 0, 'countryId' => 46),
);
// Sort votes in descending order (most on top)
function voteSort($a, $b) {
    if ($a['votes'] == $b['votes']) {
        return 0;
    }
    return ($a['votes'] < $b['votes']) ? 1 : -1;
}
// Re-organize the array with country as top level
$byCountry = array();
foreach ($entries as $entry) {
    $byCountry[$entry['countryId']][] = array(
        'entryId' => $entry['entryId'],
        'votes'   => $entry['votes']
    );
}
// For each country, sort by votes
foreach ($byCountry as $index => $country) {
    usort($byCountry[$index], 'voteSort');
}

应该可以。

您可以通过以下方式按唯一的国家id分割数组:

$entries = array(
 array('entryID' => 1, 'votes' => 3, 'countryID' => 46),
 array('entryID' => 4, 'votes' => 1, 'countryID' => 2),
 array('entryID' => 2, 'votes' => 0, 'countryID' => 46),
 array('entryID' => 5, 'votes' => 0, 'countryID' => 46),
);
$entriesByCountry = array();
foreach($entries as $entry) {
 if(!array_key_exists($entry->countyID, $entriesByCountry)
  $entriesByCountry[$entry->countyID] = array();
 $entriesByCountry[$entry->countyID][] = $entry;
}

然后按投票对每个国家数组进行排序,并取前3个。

函数ksort()将是有用的。
您可以先按排名排序,然后按国家排序。因此,您将在数组的开头放置每个国家的所有第一名,然后是第二名,以此类推。
传递给ksort的函数是

function compareVote($a,$b){
  if($a['votes'] > $b['votes'])
    return 1;
  if($a['votes'] == $b['votes']){
    if($a['countyID'] > $b['countyID'])
      return 1;
    if($a['countyID'] == $b['countyID'])
      return 0;
    return -1;
  }
return -1;
}

查看官方文档页面