从数组中获取随机项

Jam*_*mes 183 php random

$items = Array(523,3452,334,31,...5346);
Run Code Online (Sandbox Code Playgroud)

该数组的每个项目都是一些数字.

我如何从中获取随机物品$items

Vin*_*ard 451

echo $items[array_rand($items)];
Run Code Online (Sandbox Code Playgroud)

array_rand()

  • @TimoHuovinen也可能有一个外星人站在你身后......它不直接涉及这个问题. (62认同)
  • 使用此内联在页面加载时从播放列表中随机选择youtube视频,效果很好:<?php $ videos = Array(0,1,2,3); echo $ videos [array_rand($ videos)]; ?> (4认同)

pas*_*ets 33

如果您不介意在其他时间再次选择相同的项目:

$items[rand(0, count($items) - 1)];

  • 当密钥不是数字时,你会如何获得一个随机项目? (9认同)
  • ...或者如果它们的键没有按顺序排列(例如,如果你有'unset`数组元素). (4认同)

小智 16

使用PHP Rand功能

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>
Run Code Online (Sandbox Code Playgroud)

更多帮助

  • 你们让这变得比它必须的更复杂...这个怎么样... $to_shuffle = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); $洗牌=洗牌($to_shuffle); $洗牌= $洗牌[0]; print_r($洗牌); (2认同)

Chr*_*phe 8

使用 array_rand()

请参阅php手册 - > http://php.net/manual/en/function.array-rand.php