从PHP关联数组中选择一个随机元素 [英] Selecting a random element from a PHP associative array

查看:90
本文介绍了从PHP关联数组中选择一个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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);

兰德只是一个数字.因此,locations [$ rand]给了我类似的东西:

Rand is just a number. So locations[$rand] gives me something like:

'1' => 'Location 1'

好的,一个assoc数组元素.此时,我不知道此assoc数组的键,因此我尝试了以下操作:

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/>\n";
}

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆