如何以更易读的方式打乱数组或字符串列表?
想象一下,您想要一个非常可读、易于编辑的项目列表,仅用逗号分隔,然后从该列表中回显 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/>";
}
输出:
Coconut
Pear
Banana
这里唯一未解决的是该列表的可读性不如我所希望的: 就我个人而言,我非常喜欢输入列表不带引号,例如 Mango
而不是 'Mango'
,意思最好是这样:
(Mango, Banana,黄瓜、梨、桃子、甜瓜、椰子)
这很容易实现吗?非常感谢您的意见。
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/>";
}
Outputs:
Coconut
Pear
Banana
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:
(Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut)
Is this easily possible? Thanks very much for your input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并非没有违反 PHP 标准。
您可以定义常量并
在数组中使用它们,但这会破坏 的命名约定PHP,作为常量应该全部大写
Not without going against PHP standards.
You could define constants such as
and use them in your array, but that would defeat the naming conventions of PHP, as constants should be all UPPERCASE
如果您想要一个可编辑列表,我建议创建一个配置文件并从那里读取列表。
例如,您可以使用 YAML 和 symfony YAML 解析器。您的列表将如下所示:
这将更好地分离您的代码和数据。从长远来看,它也更易于维护,因为您在添加或删除元素时不必接触实际代码。
或者当然,在您的情况下,您可以只拥有一个简单的文本文件,每行一个条目,并将该文件读入数组中。
如果您担心性能,可以将生成的数组序列化到磁盘或类似的东西。
If you want to have an editable list, I suggest to create a configuration file and read the list from there.
For example, you could use YAML and the symfony YAML parser. Your list would look like this:
This would be a better separation of your code and data. It would also be more maintainable in the long run, as you don't have to touch the actual code when adding or removing elements.
Or of course in your case, you could just have a simple text file with one entry per line and read the file into an array.
If you are worried about performance, you could serialize the generated array to disk or something like that.