Home  >  Article  >  Backend Development  >  PHP implementation code for randomly sorting advertisements_PHP tutorial

PHP implementation code for randomly sorting advertisements_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:29:45893browse

People who advertise are very concerned about where their ads will be placed, because this may affect the number of clicks and even whether they are displayed on the first screen. This problem is actually easy to solve, as long as the ads are displayed randomly.

How to implement the code? Here I recommend two ways to randomly display advertisements.

Process it on the backend
Sort it on the backend and then output the page. Store the advertising nodes in an array, and The array is randomly sorted, and then the sorted array is output. The reference code (PHP) is as follows:

Copy code The code is as follows:

//Use an array to store the advertisement list
$ads = array('Ad 1'
,'Ad 2'
,'Ad 3'
,'Ad 4 '
);

// Randomly sort the array
shuffle($ads);

// Output the sorted array
$html = '';
foreach ($ads as $ad) {
$html .= $ad;
}
echo $ html;

Let’s expand it. If I am the webmaster and have reserved 4 advertising slots, but only 3 are running now; I want to place a "vacant spot" in the vacant advertising slot. The advertising rental link is displayed at the end, how to deal with it? Just insert the advertising rental link after the sorting is completed.
Copy code Code As follows:

//Use an array to store the advertisement list
$ads = array('Ad 1'
,'Ad 2'
,'Ad 3'
);

// Randomly sort the array
shuffle ($ads);

// Output the sorted array
$html = '';
foreach ($ads as $ad) {
$html .= $ad;
}

//Add advertising rental link
$html .= ' Waiting for it';
echo $html;

I use this method to output 125x125 ads, because It is intuitive, reliable, and easy to process. But if you want to make the page static, it is recommended to use the JS random sorting method.

Processed on the front end
Output in the original order on the back end, and use JavaScript on the page Reorder. Assume that the HTML fragment of the page output advertising area is as follows.
Copy the code The code is as follows:

We can reorder ads through JS. The reference code is as follows:
Copy code The code is as follows:






如果有如同方法 1 那样的扩展需求, 将空广告位显示在最后, 且显示广告招租链接, 该如何处理? 这个当作课后习题吧...

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323361.htmlTechArticle投放广告的人都很关注他的广告会放在哪个位置, 因为这可能影响点击次数, 甚至是否在第一屏显示. 就这个问题, 其实很容易解决, 只要随机...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn