如何以一种更具可读性的方式随机播放数组或字符串列表? [英] How to shuffle my Array or String list in a more readable way?
问题描述
假设您想要一个可读性强,易于编辑的项目列表,并以逗号分隔,然后从该列表中回显3个随机项目。数组或字符串无关紧要。现在,我得到了以下工作(感谢webbiedave!)
Imagine you want to have a very readable, easily editable list of items, separated by comma's only, and then echo 3 random items from that list. Array or string doesnt matter. For now, I got the following working (Thanks 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/>";
}
输出:
Coconut
Pear
Banana
唯一未解决的问题是列表不是我希望的那样可读:
就个人而言,我非常喜欢输入列表不带引号,例如 Mango
而不是'Mango'
,意思是最好这样:
Only thing unsolved here is that the list is not so readable as I wished:
Personally, I very much prefer the input list to be without the quotes e.g. Mango
as opposed to 'Mango'
, meaning preferably like so:
(芒果,香蕉,黄瓜,梨,桃子,萨瑟恩瓜,椰子)
是这个很容易吗?非常感谢您的输入。
Is this easily possible? Thanks very much for your input.
推荐答案
$input = explode(',', 'Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut');
$input = array_map('trim', $input);
这篇关于如何以一种更具可读性的方式随机播放数组或字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!