开发者

How do I select random values from an array in PHP?

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was t开发者_运维百科o use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.

I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?


$result = array();
foreach( array_rand($my_array, 8) as $k ) {
  $result[] = $my_array[$k];
}


$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);

Notice that shuffle() function gives parameter as a reference and makes the changes on it.


You could use array_rand to pick the keys randomly and a foreach to gather the objects:

$objects = array();
foreach (array_rand($my_array, 8) as $key) {
    $objects[] = $my_array[$key];
}


What about?:

$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
  $x = rand(0, $count);
  $my_array[$x];
}


I just found this in our code and was hoping to find a more readable solution:

$rand = array_intersect_key($all, array_flip(array_rand($all, $count)));


You can get multiple random elements from an array with this function:

   function getRandomElements(array $array): array
    {
        $result = [];

        $count = count($array);
        for ($i = 0; $i < rand(0, $count); $i++) {
            $result[] = rand(0, $count);
        }
        $result = array_unique($result);
        sort($result);

        return $result;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜