仅显示最接近随机数的广告



我得到这个,我只想显示一个广告,但随机,如果预算更高,它的显示会有更多的变化。这是我现在的代码:

我已经有了它从 100% 计算百分比的部分,有很多小数,但我迷失了尝试显示带有计算百分比的广告并且只显示一个广告。

如果您有任何问题或类似问题,请随时提问!

@php
$advertisment = DB::table('advertisment')
->orderBy('id', 'desc')
->get();
$totalbudget = 0;
$random = rand(100, 100000000000000);
$random1 = $random / 1000000000000;
echo $random1;
echo '<br><br>';

foreach ($advertisment as $ad) {
$total = $totalbudget + $ad->budget;
$totalbudget = $total;
}
// check what advertisment is the closest to the random number given
@endphp

我想我明白了。 如果您的所有广告都有预算,并且您的random1代表百分比 (1 - 100(,则可以在现有函数中尝试此操作。 它还会计算您正在寻找的总数,只需在集合上使用 Laravelsum()功能即可。 请注意,为了清楚起见,我将广告集合重命名为复数形式。

$totalbudget = $advertisements->sum('budget');
$closest = null;
$closestAd = false
foreach ($advertisements as $ad) {
// first get percentage of total for this budget:
$thisPercent = ($ad->budget * 100) / $totalbudget;
if ($closest === null || abs($random1 - $closest) > abs($thisPercent - $random1)) {
$closest = $thisPercent;
$colsestAd = $ad;
}
}

在循环结束时,您同时拥有百分比($closest(和广告本身($closestAd(和预算(如果您愿意(($closestAd->budget(。

有一些未知数,因此此代码可能无法完全工作。 请将其用作指南并进行调整以使其为您工作。

最新更新