Select 根据 PHP 中的计数和百分比候选人

Select a candidate based on count and percentage in PHP

我有一个广告列表,我想根据旋转(代表百分比)和浏览次数来旋转它们。可以有任意数量的广告,它们列在一个多维数组中。每行是一个广告。每被浏览一次,浏览量+1。

$aAd[] = array('viewed' => 2003, 'rotation' => 70); // 70%
$aAd[] = array('viewed' => 122, 'rotation' => 30); // 30%

我正在尝试研究如何 select 根据旋转和观看次数显示下一个广告。有没有人能够帮助公式来做到这一点?

算法需要select下一个显示,它应该根据被查看的次数和应该被查看的百分比(旋转)来选择它。广告的顺序目前没有任何特定顺序。旋转表示客户希望显示广告的所需百分比。如果一个广告连续被选中两次也没关系,只要在此示例中旋转等于 70/30。请记住,可以有任意数量的广告,它们也可以分配不同的轮播。

你可以使用这个功能:

function getNextAdIndex($aAd) {
    $scores = array_map(function ($ad) { return $ad["viewed"] / $ad["rotation"]; }, $aAd);
    return array_search(min($scores), $scores);
}

它 returns $aAd 中的索引是与理想状态(基于其旋转百分比)相比观看次数最少的索引。

示例使用

$aAd[] = array('viewed' => 0, 'rotation' => 70); // 70%
$aAd[] = array('viewed' => 0, 'rotation' => 30); // 30%

// Provide the next 100 views:    
for ($i = 0; $i < 100; $i++) {
    $j = getNextAdIndex($aAd);
    echo "showing add $j\n"; // Do whatever is needed to "display" an ad here
    $aAd[$j]["viewed"]++; // Increase its number of views
}