将javascript转换为PHP函数

时间:2012-01-09 09:35:45

标签: php javascript

我想将此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>

我在PHP文件中尝试了这个PHP函数,并且认为我可以从HTML文件中调用它的结果,因此只有确定的值才会出现在HTML源代码中。但是,这段代码打破了这个页面。

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];
}   

2 个答案:

答案 0 :(得分:1)

$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];

答案 1 :(得分:1)

注意我使用mt_rand而不是rand。它通常被认为是一个更好的随机数函数。

<?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];
?>