我一直在尝试从数组中选择随机项而不重复相同的项。
样本数组
$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/