21286 Posts in 5733 Topics by 2602 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 925 Views |
-
displaying random images on page

15 June 2010 at 4:23am
Hello,
From elsewhere on the forums I've put together this function:
and I'm displaying them in my template like so:function RandomImages(){
$items = DataObject::get("Image","ParentID=6", false, "")->toArray();
$random_images = new DataObjectSet();
while($random_images->Count() <=1)
{
$random_index = rand(0,sizeof($items)-1);
$random_images->push($items[$random_index]); //<-Problematic line of code
unset($items[$random_index]);
}
return $random_images;
}<% control RandomImages %>
<a class="thickbox" href="$Filename" >
<img src="<% control SetWidth(220) %>$URL<% end_control %>" alt="$Title" />
</a>
<% end_control %>My pages display properly most of the time, however every once in a while I will get an error '[Notice] Undefined Offset'. I suspect that the problem might be that it only occurs when the same random value is chosen twice in a row and that the 'unset($items[$random_index]);' line is what is causing the error. Once taking this line out, I cannot recreate the error, but instead on occasion I get the same 2 pictures on the page. What would be the proper way to avoid the same random numbers?
Thanks!
-
Re: displaying random images on page

4 March 2011 at 12:18am
in case someone's still interested:
using 'unset' won't rearrange the indexes in the array. use array_splice instead.
see http://www.webmasterworld.com/php/3632117.htm -
Re: displaying random images on page

4 March 2011 at 1:13am
function RandomImages(){
$limit = 50;
$items = DataObject::get("Image", "ParentID=6", "RAND()", null, $limit);
return $items;
} -
Re: displaying random images on page

4 March 2011 at 2:05am
i guess this will give you duplicates, no?
-
Re: displaying random images on page

7 May 2011 at 3:02am Last edited: 7 May 2011 3:04am
"in case someone's still interested:
using 'unset' won't rearrange the indexes in the array. use array_splice instead.
see http://www.webmasterworld.com/php/3632117.html"the link is no best... i think...
Not understand how relolve problem with array_splice MY CASE:
function RandomPerguntasItems()
{
$list_dim=5;
$items = $this->Problemas()->toArray();
$random_perguntas = new DataObjectSet();while($random_perguntas->Count() <= ($list_dim-1) )
{
$random_index = rand(0,sizeof($items)-1);
$random_perguntas->push($items[$random_index]);
array_splice($items , count($items), 5 );
//unset($items[$random_index]);
//if($items[$random_index]< $random_perguntas->Count()){$random_perguntas->Count() + $items[$random_index];}
}
return $random_perguntas;
| 925 Views | ||
|
Page:
1
|
Go to Top |




