从 PHP 关联数组中选择一个随机元素 [英] Selecting a random element from a PHP associative array
问题描述
我在 PHP 中有一个关联数组,想从中选择一个随机键/值对.这是我到目前为止所拥有的:
I've got an associative array in PHP and want to select a random key/value pair out of it. Here's what I have so far:
初始化.
$locations = array();
遍历 SQL 查询并添加键/值对:
Loops through a SQL query and adds key/val pairs:
array_push($locations, "'$location_id' => '$location_name'");
稍后,我选择数组的随机索引:
Later on, I select a random index of the array:
$rand = array_rand($locations);
兰特只是一个数字.所以 location[$rand] 给了我类似的东西:
Rand is just a number. So locations[$rand] gives me something like:
'1' => 'Location 1'
好的,一个关联数组元素.此时,我不知道这个assoc数组的key,所以我尝试了以下事情:
OK great, an assoc array element. At this point, I do not know the key of this assoc array, so I've tried the following things:
foreach($locations[$rand] as $loc_id => $location_name) {
echo "$key : $value<br/>
";
}
$loc_id, $location_name = each($locations[$rand]);
$location_name = $locations[key($rand)];
这 3 次尝试均无效.它们都会抛出诸如传递的变量不是数组"之类的错误.
None of these 3 attempts work. They all throw errors like "Passed variable is not an array".
我确信有一些简单的 1 衬垫可以从数组中提取随机键/值对.或者我的语法关闭了.我非常感谢您的帮助.
I'm sure there's some simple 1 liner that can pluck a random key/value pair from the array. Or my syntax is off. I'd really appreciate the help.
推荐答案
$array = array('a' => 1, 'b' => 2);
$key = array_rand($array);
$value = $array[$key];
这篇关于从 PHP 关联数组中选择一个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!