Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何洗牌&;从一个字符串中回显5个随机元素?_Php_String_Random_Random Sample - Fatal编程技术网

Php 如何洗牌&;从一个字符串中回显5个随机元素?

Php 如何洗牌&;从一个字符串中回显5个随机元素?,php,string,random,random-sample,Php,String,Random,Random Sample,关于从200个单词的大字符串中随机抽取三个单词的问题: $trans = __("water paradise, chicken wing, banana beach, tree trunk")?> // $trans becomes "water paradijs, kippenvleugel, bananen strand, boom tak" // elements are separated by comma's and a space 现在想象一下,我想从$trans字符串中获

关于从200个单词的大字符串中随机抽取三个单词的问题:

$trans = __("water paradise, chicken wing, banana beach, tree trunk")?>
// $trans becomes "water paradijs, kippenvleugel, bananen strand, boom tak"
// elements are separated by comma's and a space
现在想象一下,我想从$trans字符串中获取5个随机元素,并回显该
我该怎么做?欢迎使用代码!请在回答中保留以下语法:

$trans
=原始字符串

$shufl
=5个元素的选择性洗牌
包含例如Kippenvluegel、boom tak等,以便更好地理解。什么是随机字符串

是否可以:

  • “水上乐园”“Kippenvluegel”“巴纳宁街”
或者也可能是这样

  • “水链”Kippenvluegel bananen等

您可以通过使用
split
创建一个字符串数组,然后使用
shuffle
将其洗牌来实现这一点:

# Split the string into different elements
$strings = split(',', $trans);
# Shuffle the array
shuffle($strings);

# Select 5 elements
$shufl = array_slice($strings,  0, 5);
array\u slice
然后用于获取无序数组的前5个元素。另一种可能是在拆分数组上使用
array\u rand

$shufl = array_rand(array_flip($strings), 5);
$array=explode(',',$trans);
洗牌($数组);
对于($i=0;$i<5;$i++){
$shufl[]=$array[$i];
}
这将产生一个包含5个随机元素的$shufl数组

希望这有帮助:)

$array = explode ( ',',$trans);
shuffle($array);
for ( $i = 0 ; $i < 5 ; $i ++ ){
   $shufl[] = $array[$i];
}