获取相同的mt_rand值

时间:2016-04-03 08:44:33

标签: php

这是我第一次在这里提问,如果我的英语不好或我在这里做错了,我道歉。 我会问一个简单的问题,我怎样才能得到mt_rand的相同值?例如:

$array = [
          array('colour' => 'Green', 'type' => 'BMW'), 
          array('colour' => 'Blue', 'type' => 'Toyota')
         ];
$random = $array[mt_rand(0, count($array) - 1];

echo 'That car is ' . $random['type'] . ' with colour ' . $random['colour'];

但有时,它会给出结果'那辆车是带有蓝色的宝马'。我希望它在我回应它时给出正确的颜色,就像汽车是宝马,颜色是绿色,如果汽车是丰田,它会给出蓝色。我希望你能理解我的意思。感谢您阅读此内容......

1 个答案:

答案 0 :(得分:0)

使用array_rand从阵列中获取随机密钥更容易。

实施例

$cars = [
    [
        'colour' => 'Green',
        'type' => 'BMW'
    ], 
    [
        'colour' => 'Blue',
        'type' => 'Toyota'
    ]
];

$randomCarKey = array_rand($cars);
// will be one of 0,1

$randomCar = $cars[$randomCarKey];

print 'That car is ' . $randomCar['type'] . ' with colour ' . $randomCar['colour'];

将输出

That car is BMW with colour Green

如果您希望mt_rand获取随机密钥,并使用它,

$randomKey = mt_rand(0, count($cars) - 1);
$randomCar = $cars[$randomCarKey];

print PHP_EOL . 'That car is ' . $randomCar['type'] . ' with colour ' . $randomCar['colour'];

将输出

That car is Toyota with colour Blue