随机化HTML字符串输出

时间:2014-08-27 13:17:25

标签: php html arrays wordpress random

<?php 
    $random1 = '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>';
    $random2 = '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>';
    $random3 = '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>';
    echo(rand($random1, $random2, $random3));
?>

所以我写了上面的代码。我希望我的代码随机化出现的引用。是否有一种用户友好的方式在网站中实现这一点?

我在Wordpress中建立了一个网站,我想知道Wordpress(或PHP)是否有更简单的随机化输出方法。

4 个答案:

答案 0 :(得分:11)

或者,您可以定义一个包含HTML字符串的数组,然后使用array_rand()函数来获取随机条目/元素。例如:

// set of elements with random quotes
$quotes = array(
    '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>',
);

// apply array_rand function
echo $quotes[array_rand($quotes)];

答案 1 :(得分:0)

$random = array();

$random[] = '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>';
$random[] = '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>';
$random[] = '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>';

shuffle($random);

foreach($random as $quote)
{
    echo $quote;
}

答案 2 :(得分:0)

我会用这样的东西:

<?php 
$quotes = array(
    '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>'
);

echo($quotes[mt_rand(0, (count($quotes) - 1))]);

&GT;

答案 3 :(得分:0)

你也可以干净利落地做到这一点:

$quotes = array(
    '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2>    <h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
    '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>',
);

echo $quotes[rand(0,2)]; // 0-2 (Since array's start on 0)
相关问题