来自foreach的php随机顺序

时间:2023-04-10
本文介绍了来自foreach的php随机顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一些 foreach,这可以很好地工作

I have some foreach, this could work well

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

现在我想洗牌 foreach.我试过了:

Now I want shuffle the foreach. I tried:

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 provided for foreach() 在第二个 foreach 中.如何从 foreach 中随机排序?

All these caused Warning: Invalid argument supplied for foreach() in second foreach. How to random order from a foreach?

推荐答案

查看 shuffle().它接受一个对数组的 reference 并将其改组到位.所以需要在数组上使用,然后迭代:

Take a look at the documentation for shuffle(). It takes a reference to an array and shuffles it in place. So you need to use it on the array, then iterate:

shuffle($umm);

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

这篇关于来自foreach的php随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:千篇一律的foreach优化 下一篇:php PDO fetchAll() - 虽然不工作,但 foreach 工作

相关文章