我创建了一个函数,该函数从硬编码的单词列表中随机生成一个短语.我有一个函数get_words(),该函数具有一串硬编码的单词,将其转换成一个数组,然后重新排列并返回.
get_words()由generate_random_phrase()调用,它会反复遍历get_words()n次,并且在每次迭代时,将n个单词连接到最终的短语中,该短语最终将返回给用户.
我的问题是,由于某种原因,PHP一直给我不一致的结果.它的确给了我一些随机的单词,但给出的单词数量却不一致.我将4个单词指定为默认单词,它给我的短语是1-4个单词,而不是4个单词.该程序非常简单,几乎难以置信,我无法查明确切的问题.似乎链中断开的链接是正在索引的$words数组,似乎由于某种原因有时索引编制失败.我不熟悉PHP,有人可以向我解释吗?
function generate_random_phrase() {
$words = get_words();
$number_of_words = get_word_count();
$phrase = "";
$symbols = "!@#$%^&*()";
echo print_r($phrase);
for ($i = 0;$i < $number_of_words;$i++) {
$phrase .= " ".$words[$i];
}
if (isset($_POST['include_numbers']))
$phrase = $phrase.rand(0, 9);
if (isset($_POST['include_symbols']))
$phrase = $phrase.$symbols[rand(0, 9)];
return $phrase;
}
function get_word_count() {
if ($_POST['word_count'] < 1 || $_POST['word_count'] > 9)
$word_count = 4; #default
else
$word_count = $_POST['word_count'];
return $word_count;
}
function get_words() {
$BASE_WORDS = "my sentence really hope you
like narwhales bacon at midnight but only
ferver where can paper laptops spoon door knobs
head phones watches barbeque not say";
$words = explode(' ', $BASE_WORDS);
shuffle($words);
return $words;
}
?>
解决方法:
在$BASE_WORDS中,选项卡和换行符在爆炸数组中占据了空间,这就是原因.删除换行符和选项卡,它将生成正确的答案.即:
$BASE_WORDS = "my sentence really hope you like narwhales bacon at midnight but only ferver where can paper laptops spoon door knobs head phones watches barbeque not say";
标签:arrays,php
来源: https://codeday.me/bug/20191029/1957295.html