PHP:array_rand数组

时间:2015-10-26 20:29:00

标签: php arrays random multidimensional-array

我有这个数组:

$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 个答案:

答案 0 :(得分: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)];
}