在两个 PHP 函数之间随机切换


Randomly switch between two PHP functions

我在网页上有 2 个 PHP 函数。我想随机运行这两个函数之一。我知道如何使用PHP使用div或HTML,但不知道如何随机运行PHP函数。我想使用PHP而不是Javascript。

这是我的 2 个函数:

<?php get_template_part('module_sidebar_1'); ?>
<?php get_template_part('module_sidebar_2'); ?>

使用 mt_rand(); 在末尾生成数字。

<?php get_template_part('module_sidebar_'.mt_rand(1,2)); ?>

这将随机选择您的两个模板之一。

要使用单词而不是数字,只需使用数组。创建一个模板名称数组,然后使用 mt_rand 作为数组键。

$array = ['module_sidebar_sondage', 'module_sid‌​ebar_bon_plan'];
get_template_part($array[mt_rand(0,1)]);

如果您还有混合(数字 + 非数字)模板名称,创建一个包含所有模板名称的数组,例如,

$templates = ['module_sidebar_1','module_sidebar_2','module_sidebar_non_numeric'];

并通过以下方式调用随机模板文件

<?php get_template_part($templates[array_rand($templates)])?>

这样的事情呢?

$random = rand(0,1);
if ($random == 0){
    get_template_part('module_sidebar_1');
}
else{
    get_template_part('module_sidebar_2');
}