Sam*_*Sam 0 php arrays string random shuffle
想象一下,您希望拥有一个非常易读且易于编辑的项目列表,仅以逗号分隔,然后从该列表中回显3个随机项目.数组或字符串无关紧要.现在,我得到了以下工作(感谢webbiedave!)
$fruits = array('Mango', 'Banana', 'Cucumber', 'Pear', 'Peach', 'Coconut');
$keys = array_rand($fruits, 3); // get 3 random keys from your array
foreach ($keys as $key) { // cycle through the keys to get the values
echo $fruits[$key] . "<br/>";
}
Run Code Online (Sandbox Code Playgroud)
输出:
Coconut
Pear
Banana
Run Code Online (Sandbox Code Playgroud)
这里唯一未解决的是列表不是我想要的那样可读:就个人而言,我更喜欢输入列表没有引号,例如Mango相反'Mango',意思是最好像这样:
(Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut)
这很容易吗?非常感谢您的投入.
$input = explode(',', 'Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut');
$input = array_map('trim', $input);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
707 次 |
| 最近记录: |