我努力从数组中获取9个随机值,我有这个PHP代码可以正常工作但返回所有值。我只需要用foreach选择9个随机的。
<?php
foreach($gallerystreamobjects as $smallgallery) {
$smallgalleryArray = $smallgallery->GalleryPictures;
}
$arr = explode(",", $smallgalleryArray);
foreach($arr as $value)
{
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
?>
答案 0 :(得分:2)
函数array_rand()将解决您的问题:
$randomKeys = array_rand($arr, 9);
foreach($randomKeys AS $key){
$value = $arr[$key];
//do whatever you like
}
答案 1 :(得分:0)
我设法使用一种快速简便的方法来做到这一点。不是它的正确方法,但是ja,所以我尝试了array_rand()但是我一直在以最基本的方式获取错误,我发现它与实际上缺失的值有关。这是我目前的解决方案:
<?php
$smallgalleryArray = $gallerystreamobjects[0]->GalleryPictures;
$arr = explode(",", $smallgalleryArray);
shuffle($arr);
$count=0;
foreach($arr as $value) {
$count++;
if($count<10){
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
}
?>