来自foreach的php随机顺序

时间:2012-01-23 00:26:10

标签: php random foreach shuffle

我有一些foreach,这可能很好用

foreach ($umm as $data) {
        echo '<img src="'.$data->picture.'" />';
        echo  $data->id;
}

现在我想改变一下foreach。我试过了:

foreach (shuffle($umm) as $data) {
        echo '<img src="'.$data->picture.'" />';
        echo  $data->id;
}

foreach ($umm as $data) {
        $rand_pic[] = $data->picture;
        $rand_id[] = $data->id;
}
$ran = shuffle($rand_id);
foreach($ran as $new){
    echo '<img src="'.$new->picture.'" width="100" />';
    echo $new->id;
}

所有这些都导致Warning: Invalid argument supplied for foreach()foreach。如何从foreach中随机排序?

3 个答案:

答案 0 :(得分:32)

看看the documentation for shuffle()。它需要一个引用到一个数组并将其混洗到位。所以你需要在数组上使用它,然后迭代:

shuffle($umm);

foreach ($umm as $data) {
        echo '<img src="'.$data->picture.'" />';
        echo  $data->id;
}

答案 1 :(得分:3)

shuffle()返回一个布尔值 - 你通过引用传递数组

试试这个:

shuffle($umm);
foreach($umm as $new){
    echo '<img src="'.$new->picture.'" width="100" />';
    echo $new->id;
}

答案 2 :(得分:0)

试试这个Shuffle:

&#13;
&#13;
<?php 
   shuffle($umm);
   foreach($umm as $key => $value): ?>
	<img src="<?php echo $value->picture; ?>" alt="<?php echo $value->title;?>" />
	<?php echo $value->id;?>	  
<?php endforeach; ?>
&#13;
&#13;
&#13;