php从数组中选择多个随机键

标签 php arrays random

我一直在尝试从数组中选择随机项而不重复相同的项。

样本数组

$images=array();
$images[]=array('img'=>'bands.jpg','cat'=>'bands.php');
$images[]=array('img'=>'cake.jpg','cat'=>'cakes.php');
$images[]=array('img'=>'catering.jpg','cat'=>'catering.php');
$images[]=array('img'=>'dj.jpg','cat'=>'djs.php');
$images[]=array('img'=>'dress.jpg','cat'=>'dress_attire.php');
$images[]=array('img'=>'limos.jpg','cat'=>'limos_transportaion.php');
$images[]=array('img'=>'photography.jpg','cat'=>'photography.php');
$images[]=array('img'=>'venues.jpg','cat'=>'venues.php');
$images[]=array('img'=>'wedding_planer.jpg','cat'=>'planning.php');

我已经尝试了以下方法,但由于某些原因它无法正常工作。它只是将数组中的第一项收集到呈现的计数。 //$adDisplay 是一个介于 1-9 之间的数字

$rand = array_rand($images, $adDisplay);
foreach($rand as $key => $value){
    echo'<a href="'.$images[$key]['cat'].'"><img src="img/banners/'.$images[$key]['img'].'" border="0" alt="" /></a>';
}

最佳答案

有很多方法可以做到这一点,我可能会洗牌然后切片:

$images = array();
$images[]=array('img'=>'bands.jpg','cat'=>'bands.php');
$images[]=array('img'=>'cake.jpg','cat'=>'cakes.php');
$images[]=array('img'=>'catering.jpg','cat'=>'catering.php');
$images[]=array('img'=>'dj.jpg','cat'=>'djs.php');
$images[]=array('img'=>'dress.jpg','cat'=>'dress_attire.php');
$images[]=array('img'=>'limos.jpg','cat'=>'limos_transportaion.php');
$images[]=array('img'=>'photography.jpg','cat'=>'photography.php');
$images[]=array('img'=>'venues.jpg','cat'=>'venues.php');
$images[]=array('img'=>'wedding_planer.jpg','cat'=>'planning.php');

shuffle($images);

$adDisplay = 5;

foreach( array_slice($images,0,$adDisplay) as $image){
    echo '<a href="' . htmlspecialchars($image['cat']) . '">'
         . '<img src="img/banners/'
         . htmlspecialchars($image['img']) . ' border="0" alt="" />'
         . '</a>';
}

关于php从数组中选择多个随机键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13997826/

相关文章:

php - Laravel 5 - 是否可以在不使用 Eloquent 或 Artisan 的情况下使用 MySQL 数据库?

php - 获取 MySql 数据并将其存储到 Javascript 数组中

java - 通用数组创建错误

python - 从两个数组中获取相同数量的元素,使得所取值的重复项尽可能少

javascript - 如何在返回值之前等待 for 循环中的 Promise 完成

javascript - 降低从与前一个相同的数组中获取随机项的概率

javascript - 将滚动条放到 div 上,并将获取的数据放入其中

php - 在 PHP 中寻找流氓 &lt;!---->

haskell - Haskell和State Monad的随机数序列,我做错了什么?

matlab - 在 Parfor 循环中生成扰乱的准蒙特卡罗数的问题