开发者

mixing an array within a PHP foreach loop

I'm trying to display an array in a random order in a foreach loop in PHP. I don't know whether to create a randomizing loop to do this or whether there is a randomizing function. I'm capturing information from the Facebook and twitter api's with the goal to mix the results and display as a list of comments from Facebook wall and tweets from twitter.

As you can see below, I first merge the two arrays from Facebook and twitter into one, and then loop through them in a foreach loop to display. currently all the Facebook one show first, and then twitter. I want to mix the two randomly. Sorry about the code, I hacked it together pretty quickly.

If you've got a totally different way to do this as well please don't hold back, I'm all ears! ;)

Here is what I have code wize:

$array = array_merge ($comments, $tweets);
foreach ($array as $commentortweet) 
{
    echo '<li>'. $commentortweet->picture. $commentortweet->message . $commentortweet->开发者_如何学JAVAupdatetime . 
        $commentortweet->content. $commentortweet->user . $commentortweet->author .'</li>';
}
echo '</ul>'; 


You can use your method of merging the two arrays then shuffle them using shuffle($array). You may then loop through the new order and print them out.


Use shuffle to randomize :

foreach (shuffle($array) as $commentortweet) {
....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜