2015-06-23 48 views
1

我正在使用暱稱生成器工具。我有兩個.json文件,第一個和第二個音節的數組。PHP:檢查兩個隨機單詞是否不相同

第一個音節=單詞的開頭。

第二個音節=單詞的結尾。

下面是工具如何生成一個隨機的暱稱:

$name = ucwords($first_syllable[rand(0, count($first_syllable) - 1)] . $second_syllable[rand(0, count($second_syllable) - 1)]); 

這工作得很好,但現在我需要檢查第一個音節是不一樣的第二個。

例如,我在數組中有第一個音節「Dal」,我也有第二個音節「Dal」。我不希望該工具生成「Daldal」。這就是爲什麼我需要檢查第一個音節是否與第二個音節不同。

任何幫助非常感謝。

回答

4

只是檢查它們是否相同或不 -

$name1 = $first_syllable[rand(0, count($first_syllable) - 1)]; 
$name2 = $second_syllable[rand(0, count($second_syllable) - 1)]; 

if (strtolower($name1) !== strtolower($name2)) { 
    $name = ucwords($name1 . $name2); 
} 
1
$firstS = ucwords($first_syllable[rand(0, count($first_syllable) - 1)]); 
$secondS = ucwords($second_syllable[rand(0, count($second_syllable) - 1)]); 

if($firstS != $secondS) 
    $name = $firstS.$secondS; 
1

最簡單的解決方法是,直到它們是不同的存儲所選擇的變量值,然後循環。

循環將確保您的兩個值不同。

的代碼示例(未測試):

<?php 
$second_syllable_value = ''; 
$first_syllable_value = ''; 
while ($second_syllable_value == $first_syllable_value) 
{ 
    $first_syllable_value = $second_syllable[rand(0, count($second_syllable) - 1)]; 
    $second_syllable_value = $second_syllable[rand(0, count($second_syllable) - 1)]; 
} 
?> 

小心的長度的陣列的,因爲你可以在一個無限循環結束。