2008-11-11 109 views
2
$images = array(); 
$images[0][0] = "boxes/blue.jpg"; 
$images[0][1] = "blah.html"; 
$images[1][0] = "boxes/green.jpg"; 
$images[1][1] = "blah.html"; 
$images[2][0] = "boxes/orange.jpg"; 
$images[2][1] = "blah.html"; 
$images[3][0] = "boxes/pink.jpg"; 
$images[3][1] = "blah.html"; 
$images[4][0] = "boxes/purple.jpg"; 
$images[4][1] = "blah.html"; 
$images[5][0] = "boxes/red.jpg"; 
$images[5][1] = "blah.html"; 
$images[6][0] = "boxes/yellow.jpg"; 
$images[6][1] = "blah.html"; 

$i = 0; 


*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>"; 

$boxes = array(); 
while($i<5) 
{ 
    $rand = rand(0,(sizeof($images)-1)); 
    //echo $rand; 
    $slice = array_splice($images, $rand); 
    $boxes[$i] = $slice; 
    $i++; 
}* 

我想获得一个随机图像选择器从$图像数组提供的图像列表中选择。但是,我无法使用“数组”之外的任何其他值填充$ box数组。谁能告诉我为什么?随机图像选择器PHP

我现在用下面的代码的任何帮助深表感谢

UPDATE和它打破每当它遇到一个空元素。除非我非常误会,不应该拼凑这样的洞?

$rand = rand(0,(sizeof($images))); 
array_splice($images, $rand); 
$i = 0; 
while($i<5) 
{ 
    echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>"; 
    $i++; 
} 

回答

2

稍微偏离主题,但不会是在这种情况下更容易(从6)列表中挑选5个项目只是选择一个元素并将其从原始数组中丢弃,然后使用原始数据?这也将确保您不会在结果数组中获得重复项。

我意识到你原来可能有6个以上的项目,可能要少于5个,但我特别针对所发布的示例进行了讨论。

+0

这不是一个坏主意。这肯定会更容易。 – Drew 2008-11-11 12:04:11

0

array_splice()返回一个数组。

你可以尝试这样的事情:

while($i<5) 
{ 
     $rand = rand(0,(sizeof($images)-1)); 
     $boxes[$i] = $images[$rand]; 
     $i++; 
} 
4

这可能是做这件事的更好的方式:

foreach (array_rand($images, 5) as $key) { 
    $boxes[] = $images[$key]; 
}