问题
a question about getting three random words out of a big string of say 200 words:
$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
Now imagine I want to get 5 random elements from that $trans string and echo that.
How can I do that? Code is welcome! Please keep this syntax in your answer:
$trans
= the original string
$shufl
= selective shuffle of 5 elements
contains e.g kippenvleugel, boom tak
回答1:
You can do this by creating an array of strings using split
, and then shuffling it with 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_slice
is then used to get the first 5 elements of the shuffled array. Another possibility is to use array_rand
on the split array:
$shufl = array_rand(array_flip($strings), 5);
回答2:
$array = explode ( ',',$trans);
shuffle($array);
for ( $i = 0 ; $i < 5 ; $i ++ ){
$shufl[] = $array[$i];
}
This will result in a $shufl array containing your 5 random elements.
Hope this helps :)
回答3:
For better understanding. What is a random string?
Can it be:
- 'water paradijs' 'kippenvleugel' 'bananen strand'
or can it also be
- 'water strand' 'kippenvleugel bananen', etc.
?
来源:https://stackoverflow.com/questions/5156428/how-to-shuffle-echo-5-random-elements-from-a-string