Jump to content

[SOLVED] Select and Display Random Elements from Array


Omzy

Recommended Posts

Lets say I have a multi-dimensional array, as such:

 

 
$cats=array(
'flowers'=>array('Flowers', 'Flower Decorations'),
'balloons'=>array( 'Balloons', 'Balloon Decorations'),
'banners'=>array('Banners', 'Banner Decorations'),
'fruit-displays'=>array('Fruit Displays', 'Fruit Display Decorations'),
'ice-sculptures'=>array('Ice Sculptures', 'Ice Sculpture Decorations'),
);

 

And currently I'm displaying this data like this:

 

foreach($cats as $index => $value)
{
echo '<p><a href="/directory/'.$index.'/">'.$value[0].'</a> - '.$value[1].'</p>';
}

 

So this just displays all the array elements in the order they are in the array. But I now need some code that will select and display any 3 elements from this array.

 

I know I can use the shuffle() function to randomize the array but this means I lose my array indexes. Surely there is a simple way of doing this, I like to have minimal code and prefer to use PHPs in-built functions to accomplish simple tasks, rather than having to code a whole new function that does the same thing :-)

Take a look at array_rand()

 

It will take the array anda  number of keys to take from the array

 

php.net's example;

 

<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

Have you tried it? as I beg to differ

 

$cats=array(
'flowers'=>array('Flowers', 'Flower Decorations'),
'balloons'=>array( 'Balloons', 'Balloon Decorations'),
'banners'=>array('Banners', 'Banner Decorations'),
'fruit-displays'=>array('Fruit Displays', 'Fruit Display Decorations'),
'ice-sculptures'=>array('Ice Sculptures', 'Ice Sculpture Decorations'),
);

$rand_keys = array_rand($cats, 3);

foreach($rand_keys as $value)
{
echo '<p><a href="/directory/'.$value.'/">'.$cats[$value][0].'</a> - '.$cats[$value][1].'</p>';
}

  • 1 month later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.