简体   繁体   English

获取相同的mt_rand值

[英]Get the same value of mt_rand

This is the first time I ask a question here, I apologise if my English is bad or i did something wrong here. 这是我第一次在这里提出问题,对于我的英语不好或者我在这里做错了事,我深表歉意。 I would ask a simple question, how can I get the same value of mt_rand? 我会问一个简单的问题,我如何获得相同的mt_rand值? Example: 例:

 $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']; 

But sometimes, it gives the result 'That car is BMW with colour Blue'. 但是有时候,它的结果是“那辆汽车是蓝色的宝马”。 I want it gives the right colour when i echo it, like if the car is BMW, the colour is Green, and if the car is Toyota, it gives colour Blue. 我希望它在回声时能给出正确的颜色,例如如果汽车是宝马,则颜色是绿色,如果汽车是丰田,则它会给出蓝色。 I hope you can understand what i meant. 我希望你能理解我的意思。 Thanks for reading this... 感谢您阅读...

It's easier to use array_rand to get a random key from your array. 使用array_rand从数组中获取随机密钥会更容易。

Example

$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'];

Will output 将输出

That car is BMW with colour Green

If you prefer mt_rand here's how you can get a random key, and use it 如果您更喜欢mt_rand ,可以通过以下方法获取随机密钥并使用它

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

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

Will output 将输出

That car is Toyota with colour Blue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM