我设置了一个事件循环;我也设置了广告循环。
我想注入每个广告'进入随机点的事件循环。这些循环/数组具有不同的设置,因此无法进入循环/数组。
我有以下设置,这往往有效,但在ad.inc中,它是一个随机的广告...而应该是获得广告的总数并将它们随机地注入到事件中,直到该计数为止达到。
$count = 1;
$total = count($events);
$random = rand(3, $total);
foreach ($events as $event) {
include('./inc/events-item.inc');
if ($count == $random) {
include("./inc/ad.inc");
$random = rand($count, $total);
}
$count++;
}
例如,如果我的总事件数为30,而我的广告总数为4,那么我应该会看到这四个广告随机注入到30个事件中。
任何帮助?
答案 0 :(得分:3)
为广告创建所有排名的数组。如果你有30个广告 - 有30个位置,从0到29:
$positions = range(0, 29);
// now get 4 random elements from this array:
$rand_positions = array_rand($positions, 4);
// though `array_rand` returns array of keys
// in this case keys are the same as values
// iterate over your events and if counter equals
// to any value in $rand_positions - show ad
$i = 0;
foreach ($events as $event) {
include('./inc/events-item.inc');
if (in_array($i, $rand_positions, true)) {
include("./inc/ad.inc");
}
$i++;
}
答案 1 :(得分:0)
您需要随机选择4个(或者您拥有的广告数量)在30个(或者您拥有的条目数量)之间的其他点数。这是一个可能的解决方案。
// Set up counts
$entry_count = count($events);
$ad_count = 4;
// Create an array of entry indices, and an array of ad indices
$entry_indices = range(0, $entry_count - 1);
$ad_indices = array();
// Fill the ad indices with random elements from the entry indices
for ($i = 0; $i < $ad_count; $i++) {
$entry = rand(0, count($entry_indices));
array_push($ad_indices, $entry_indices[$entry]);
array_splice($entry_indices, $entry, 1);
}
// Sort it so we only need to look at the first element
sort($ad_indices);
// Iterate through the events
$count = 0;
foreach ($events as $event) {
include('./inc/events-item.inc');
// If we have any ad indices left, see if this entry is one of them
if (count($ad_indices) > 0 && $count == $ad_indices[0]) {
include("./inc/ad.inc");
array_shift($ad_indices);
}
$count++;
}