How to shuffle my Array or String list in a more readable way?

懵懂的女人 提交于 2019-12-11 19:31:21

问题


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.


回答1:


$input = explode(',', 'Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut');
$input = array_map('trim', $input);



回答2:


Not without going against PHP standards.

You could define constants such as

define(Mango, "Mango");

and use them in your array, but that would defeat the naming conventions of PHP, as constants should be all UPPERCASE




回答3:


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:

- Mango
- Banana
- Cucumber
- Pear
- Peach
- Coconut

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.



来源:https://stackoverflow.com/questions/4857185/how-to-shuffle-my-array-or-string-list-in-a-more-readable-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!