PHP如何在占位符数组中随机循环

时间:2018-03-10 23:04:15

标签: php wordpress loops

我的wordpress网站上有一个搜索输入,每次页面刷新时我想显示不同的地方信息。所以我将得到一个不同值的数组,这个函数将在数组中随机循环,我认为我的问题在于结果。我使用插件进行搜索输入,因此要定义例如占位符会说“你好”,我需要这样做:

$item['textinput']= "hello";

所以我需要结果:

$item['textinput']= $placeholders;

我正在添加整个代码:

$placeholders = array("yo i hio", "and him", "nayo jones");


 function randominputs($input){

    $i=1;
     while($i<=20){
     $randNum =  rand(1,100);

  if($input==$i){

     $item['textinput']= $placeholders; 
   }

    $i++;
 }
}

由于

3 个答案:

答案 0 :(得分:3)

使用array_rand

$placeholder = $placeholders[array_rand($placeholders)];

答案 1 :(得分:1)

我建议将sizeof()调用添加到您的代码中。

例如,如果我想从数组中调用随机结果,您可以尝试...

       $arr = array("1", "2", "3", "4", "5", "6", "7");

       $len = sizeof($arr) - 1; // account for the 0 position

       $rand = rand(0,$len);

       echo $arr[$rand];

答案 2 :(得分:0)

你也可以使用:

$placeholders = array("yo i hio", "and him", "nayo jones");

$randomPlaceholder = array_rand($placeholders);
$item["textinput"] = $randomPlaceholder[0];
相关问题