Selecting a random element from a PHP associative array

陌路散爱 提交于 2019-11-27 15:52:22

问题


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:

Initialize.

$locations = array();

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

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

'1' => 'Location 1'

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)];

None of these 3 attempts work. They all throw errors like "Passed variable is not an array".

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.


回答1:


$array = array('a' => 1, 'b' => 2);
$key = array_rand($array);
$value = $array[$key];



回答2:


array_rand() returns a key from the array, not a value. You can just use:

$location_name = $locations[$rand];

To get the location name.


Here's a full example: http://codepad.org/zR2YdMGN

Just click submit a few times, you'll see the random working.




回答3:


your push is wrong

$locations[$location_id] = $location_name;

it should be

so, there is nothing about selecting random element in your question.
always debug your code, just to see if you have proper data before using it



来源:https://stackoverflow.com/questions/7209127/selecting-a-random-element-from-a-php-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!