[英]convert javascript to PHP function
I would like to convert this javascript (which works correctly) into a PHP function, so that all this code does not have to appear in the source code of the webpage. 我想将这个javascript(可正常工作)转换为PHP函数,这样所有这些代码都不必出现在网页的源代码中。
<script type="text/javascript">
var images = [],
index = 0;
images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);
</script>
I tried this PHP function in the PHP file, and thought I could call its result, from the HTML file, so only determined value would appear in HTML source code. 我在PHP文件中尝试了这个PHP函数,并且认为我可以从HTML文件中调用它的结果,因此只有确定的值才会出现在HTML源代码中。 This code broke the page, though.
但是这段代码打破了这个页面。
public function getRandom()
{
$images = array();
$index = 0;
$images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
$images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
$images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
$index = Math.floor(Math.random() * $images.length);
return $images[$index];
}
$images = array(
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>"
);
$index = rand(0, count($images)-1);
echo $images[$index];
Note I use mt_rand instead of rand. 注意我使用mt_rand而不是rand。 It's generally considered a better random number function.
它通常被认为是更好的随机数函数。
<?php
$images = array();
$images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
$images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
$images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
$randIndex = mt_rand(0,sizeof($images)-1);
echo $images[$randIndex];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.