句子之间自动切换

时间:2017-03-30 08:53:05

标签: php joomla

我希望我的joomla网站能够自动更改它将回应给用户的句子,所以我写了3个不同的句子:

$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";

我希望在句子之间切换,所以我知道我不能只将$sentence1放在echo中,但我不知道如何写它。我有这样的回声线:

echo "Hey {user->name}." . "<br />" . $sentence1

顺便说一下,{user->name}来自Joomla自己的“代码”,所以工作正常:)

3 个答案:

答案 0 :(得分:2)

随机问候:

$sentence[1] = "Everything okay?";
$sentence[2] = "Have a good day";
$sentence[3] = "What are you doing today?";    

echo "Hey {user->name}." . "<br />" . $sentence[rand(1,3)]

答案 1 :(得分:1)

您可以使用随机函数,例如mt_rand()

$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
$nb = mt_rand(1, 3); // Gets a random number from 1 to 3
$sentence_shown = ${'sentence' . $nb}; // Equals $sentence1, $sentence2 or $sentence3

echo "Hey {user->name}." . "<br />" . $sentence_shown;

甚至更好,将三个字符串放在一个数组中:

$sentences = array();
$sentences[] = "Everything okay?";
$sentences[] = "Have a good day";
$sentences[] = "What are you doing today?";
$nb = mt_rand(0, 2); // Gets a random number from 0 to 2
$sentence_shown = $sentences[$nb];

echo "Hey {user->name}." . "<br />" . $sentence_shown;

答案 2 :(得分:0)

在我看来,你可以将3个句子或3个字符串放在一个数组中,然后你可以在循环时打印每个句子。例如:

$array = array(sentence1, sentence2, sentence3 , ... , sentence n);
for ($index = 0; $index < sizeof($array); $index++) {
    echo 'This is sentence ' + index ':' + $array[index];
}