1

I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the actual values from the array, e.g.

$random_elements = array();
$random_keys = array_rand($source_array);
foreach ( $random_keys as $random_key ) {
  $random_elements[] = $source_array[$random_key];
}

That seemed cumbersome to me; I was thinking I could do it more concisely. I would need either a function that plain-out returned random elements, instead of keys, or one that could convert keys to elements, so I could do something like this:

$random_elements = keys_to_elements(array_rand($source_array, $number, $source_array));

But I didn't find any such function(s) in the manual nor in googling. Am I overlooking the obvious?

4

3 回答 3

1

An alternate solution would be to shuffle the array and return a slice from the start of it.

Or, if you don't want to alter the array, you could do:

array_intersect_key($source_array, array_combine(
    array_rand($source_array, $number), range(1, $number)));

This is a bit hacky because array_intersect can work on keys or values, but not selecting keys from one array that match values in another. So, I need to use array_combine to turn those values into keys of another array.

于 2012-01-19T18:35:50.390 回答
1

What about usung array_flip? Just came to my mind:

$random_elements =  array_rand(array_flip($source_array), 3);

First we flip the array making its values become keys, and then use array_rand.

于 2012-01-19T18:42:59.710 回答
0

You could do something like this, not tested!!!

array_walk(array_rand($array, 2), create_function('&$value,$key', '$value = '.$array[$value].';'));

于 2012-01-19T18:41:30.500 回答