Multidimensional Arrays (associative) + load randomly.
June 23, 2010 Leave a comment
The assignment was to randomly display a set of data on my page (& the preferable option was to use server side scripting).
Here’s the data that needed to be displayed:
[Thumbnail1] [entry name1] [user name1]
[Thumbnail2] [entry name2] [user name3]
[Thumbnail3] [entry name3] [user name3]
The solution mentioned below users multi-dimensional arrays to achieve this.
You can refer to http://www.webcheatsheet.com/php/multidimensional_arrays.php for more details.
Here’s the solution (originally written by one of my colleagues):
<ul>
<?php
$allEntries = array(
0 => array(
“link” => “http://www.google.com”,
“thumbnail” => “http://www.google.com/intl/en_ALL/images/srpr/logo1w.png”,
“entryname” => “Google”,
“firstname” => “Google User”
),
1 => array(
“link” => “http://www.yahoo.com”,
“thumbnail” => “http://l.yimg.com/a/i/ww/met/yahoo_logo_us_061509.png”,
“entryname” => “Yahoo”,
“firstname” => “Yahoo User”
),
2=> array(
“link” => “http://www.votigo.com”,
“thumbnail” => “http://www.votigo.com/corp/img/votigo-logo.gif”,
“entryname” => “Votigo”,
“firstname” => “Votigo User”
),
3 => array(
“link” => “http://www.php.net”,
“thumbnail” => “http://static.php.net/www.php.net/images/php.gif”,
“entryname” => “Php”,
“firstname” => “Php User”
)
);
shuffle($allEntries);
?>
<?php foreach ($allEntries as $myEntry): ?>
<li>
<a href=”<?php echo $myEntry[“link”]; ?>”><img src=”<?php echo $myEntry[“thumbnail”]; ?>” width=”108″ height=”82″ alt=”<?php echo $myEntry[“firstname”]; ?>” /></a>
<strong><?php echo $myEntry[“firstname”]; ?></strong>
<i><?php echo $myEntry[“entryname”]; ?></i>
</li>
<?php endforeach; ?>
</ul>
CLICK HERE to see the result.
(refresh this page to see the results load in a random order)