2015-10-26 20 views
0

我有此數組:PHP:array_rand陣列

$nonTerminals = array("S","A","B"); 
$grammar = array(
"$nonTerminals[0]" => "aA", 
"$nonTerminals[1]" => array("aA","bB"), 
"$nonTerminals[2]" => array("bB","b") 
); 

,我用這個隨機值:

$rand_keys = array_rand($grammar, 2); 
echo $grammar[$rand_keys[0]] . "\n"; 

但這是錯誤的,因爲它給我一些錯誤。

+1

你能後你得到的錯誤?因爲現在,從我所看到的,你正試圖回顯一個數組.. –

+1

而這些錯誤是? –

+3

如果第二個或第三個被選中,你試圖回顯一個數組,可能是'Notice:Array to string conversion'。 – AbraCadaver

回答

1

你可以這樣說:

$nonTerminals = array("S","A","B"); 
$grammar = array(
"$nonTerminals[0]" => "aA", 
"$nonTerminals[1]" => array("aA","bB"), 
"$nonTerminals[2]" => array("bB","b") 
); 

$rand_keys = array_rand($grammar, 2); 
if (!is_array($grammar[$rand_keys[0]]) { 
    //This checks if the value is an array or not. 
    echo $grammar[$rand_keys[0]]; 
} 
else { 
    //it is an array, so echo a random value from that array; 
    echo $grammar[$rand_keys[0]][rand(0, 1)]; 
} 
+0

非常感謝!!! –

+0

沒問題:-)別忘了接受答案;) –

+0

done 。 再次感謝 ! –