代码之家  ›  专栏  ›  技术社区  ›  Chris B.

如何从PHP中的数组中选择随机值?

  •  4
  • Chris B.  · 技术社区  · 14 年前

    我有一个PHP对象数组。我需要随机选择其中8个。我最初的想法是 array_rand(array_flip($my_array), 8) 但这不起作用,因为对象不能作为数组的键。

    我知道我可以用 shuffle ,但我担心随着阵列大小的增加,性能会有所提高。这是最好的方法,还是有更有效的方法?

    6 回复  |  直到 7 年前
        1
  •  8
  •   VolkerK    14 年前
    $result = array();
    foreach( array_rand($my_array, 8) as $k ) {
      $result[] = $my_array[$k];
    }
    
        2
  •  6
  •   Enlightened    14 年前
    $array = array();
    shuffle($array); // randomize order of array items
    $newArray = array_slice($array, 0, 8);
    

    注意到 shuffle() 函数将参数作为引用并对其进行更改。

        3
  •  2
  •   Gumbo    14 年前

    你可以使用 array_rand 随机选择键 foreach 要收集对象:

    $objects = array();
    foreach (array_rand($my_array, 8) as $key) {
        $objects[] = $my_array[$key];
    }
    
        4
  •  0
  •   James Sumners    14 年前

    怎么样?:

    $count = count($my_array);
    for ($i = 0; $i < 8; $i++) {
      $x = rand(0, $count);
      $my_array[$x];
    }
        5
  •  0
  •   David Harkness    11 年前

    我刚刚在我们的代码中发现了这一点,并希望找到一个更可读的解决方案:

    $rand = array_intersect_key($all, array_flip(array_rand($all, $count)));
    
        6
  •  0
  •   Sebastian Viereck    7 年前

    使用此函数可以从数组中获取多个随机元素:

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