我已經創建了一個函數,它從硬編碼的單詞列表中隨機生成一個短語。我有一個功能get_words()
它有一個硬編碼字的字符串,它變成一個數組,然後洗牌並返回。Php:字符串索引不一致?
get_words()
被稱爲generate_random_phrase()
,它通過get_words()
n次迭代,並在每次迭代地連接了n個字成註定要被返回給用戶的最後一句。
我的問題是,由於某種原因,PHP不斷給我不一致的結果。它給我的話是隨機的,但它給不一致的單詞數量。我指定了4個單詞作爲默認值,它給了我1-4個單詞而不是4個單詞。這個程序非常簡單,幾乎令人難以置信,我無法準確找出確切的問題。似乎鏈中的鏈接是$words
正在被索引,似乎由於某些原因有時索引失敗。我對PHP不熟悉,有人可以向我解釋這一點嗎?
<?php
function generate_random_phrase() {
$words = get_words();
$number_of_words = get_word_count();
$phrase = "";
$symbols = "[email protected]#$%^&*()";
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;
}
?>
哇,你是個天才!謝謝 – 2014-10-05 02:02:10