Help needed for Shuffle multidimensional array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ChrisK
Forum Newbie
Posts: 9
Joined: Thu May 28, 2009 11:37 am

Help needed for Shuffle multidimensional array

Post by ChrisK »

I wanted to shuffle/randomize the multidimensional array before the content being displayed. Can you help me with this?

Code: Select all

<?php
 
 $news = array(
        array('item_title'=>'cnn', 'item_name'=>'news network'),
        array('item_title'=>'espn', 'item_name'=>'sports network'),
        array('item_title'=>'hbo', 'item_name'=>'movie network')
        );
 
/*** How to shuffle/randomize the above multidimensional array as i dont want display the elements in the same order 
cnn-news network, espn-sports network, hbo-movie network ***/
 
 /*** loop over the array ***/
 foreach( $news as $item )
 {
        echo $item['item_title'].'-'.$item['item_name'].'<br />';
 }
 
?>
 
Appeciate your help.

Thanks
Chris
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help needed for Shuffle multidimensional array

Post by requinix »

It's funny that you use the term shuffle.
ChrisK
Forum Newbie
Posts: 9
Joined: Thu May 28, 2009 11:37 am

Re: Help needed for Shuffle multidimensional array

Post by ChrisK »

tasairis: -> i tried using the shuffle like this.

$news = shuffle($news);

before the foreach loop.

but i get the following error message:

Warning: Invalid argument supplied for foreach() in /home/public_html/dev/test.php

So i am not sure shuffle() can be used in a multidimensioanl array. By the way, i am a beginner in PHP.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help needed for Shuffle multidimensional array

Post by requinix »

Did you look at that page? Especially the part that mentions "return value"?
Post Reply