This code will take the array shown and display 4 random entries in the format shown (or near enough).
Are there any parts of this that can be optimised? I'm not happy about the if
statement.
<?php
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
$i = 0;
foreach ($keys as $key) {
$random[$key] = $list[$key];
if ($i >= 3){
break;
}
$i++;
}
return $random;
}
$arr = array();
$arr[] = array('img' => "http://placehold.it/150x150", 'link' => '#1', 'text1' => "ONE 1", 'text2' => 'ONE 2');
$arr[] = array('img' => "http://placehold.it/200x150", 'link' => '#2', 'text1' => "TWO 1", 'text2' => 'TWO 2');
$arr[] = array('img' => "http://placehold.it/250x150", 'link' => '#3', 'text1' => "THREE 1", 'text2' => 'THREE 2');
$arr[] = array('img' => "http://placehold.it/300x150", 'link' => '#4', 'text1' => "FOUR 1", 'text2' => 'FOUR 2');
$arr[] = array('img' => "http://placehold.it/350x150", 'link' => '#5', 'text1' => "FIVE 1", 'text2' => 'FIVE 2');
$arr[] = array('img' => "http://placehold.it/400x150", 'link' => '#6', 'text1' => "SIX 1", 'text2' => 'SIX 2');
$arr[] = array('img' => "http://placehold.it/450x150", 'link' => '#7', 'text1' => "SEVEN 1", 'text2' => 'SEVEN 2');
foreach(shuffle_assoc($arr) as $key => $value)
{
echo '<p><img src="'.$value["img"].'"></p>';
echo '<p>'.$value["link"].'</p>';
echo '<p>'.$value["text1"].'</p>';
echo '<p>'.$value["text2"].'</p>';
echo '<hr>';
}
?>