Random image picker PHP - php

$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated
UPDATE
I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?
$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}

This might be a nicer way of doing it:
foreach (array_rand($images, 5) as $key) {
$boxes[] = $images[$key];
}

Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.
I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.

array_splice() returns an array.
You can try something like this:
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
$boxes[$i] = $images[$rand];
$i++;
}

Related

PHP - Use variable names with numbers through a loop

In my for loop for ($i = 1; $i <= 3; $i++) i have have html code that will be echod 3 times. The html also using PHP objects ($help).
$help has 3 things, $help->url_1, $help->text_1, $help->icon_1. But through the loop, I want it so that when for example $i is at 2, i want to use $help->url_2, etc. How can i sort of increment the variable name in the echo string of in the loop?
<?php
class Help
{
public $url;
public $text;
public $icon;
}
$help1 = new Help();
$help1->url = 'your url';
$help1->text = 'your text';
$help1->icon = 'url to your icon';
$helps[] = $help1;
//Repeat for other helps (help2, help3, etc.)
?>
Once you have an array of objects, you only need to loop into it using a foreach loop :
foreach ($helps as $help) {
echo "<h3>" . $help->url . "</h3>";
echo "<p>" . $help->text . "</p>";
echo "<img src='" . $help->icon . "' alt='your alt'/>";
}

How can I add a list of links to images to several dynamically generated divs (via PHP)?

I'm new to PHP and I just figured out how to generate content from several arrays to populate 40 divs. It's a product gallery and the different parts are generated via a for loop. Each time through the loop, I'm using the index to not only grab info from the arrays, but also to create a link for the entire div that I want to use as a JQuery Lightbox to show different views of each product. I've already been able to create a link to the first of the images. I've been trying to use the scandir() function, readdir() function to get a list of each image, but I haven't had any success. The images are in folders, _images/products/0/0.jpg (this folder also contains 1.jpg, 2.jpg, etc. Each time through the loop, it changes to _images/products/1/0.jpg - there are more images in this folder too. I need to create a link for each image and add it to the array in a way that will link a distinct Lightbox with each div.
$names = array ('item1', 'item2', 'item3', etc...);
$prices = array ('item1', 'item2', 'item3', etc...);
$number = array ('item1', 'item2', 'item3', etc...);
$serves = array ('item1', 'item2', 'item3', etc...);
$names_size = sizeof($names)
$img_link = "_images/products/"; // used to create the link for $div2
$div1 = "<div id=\"";
$div2 = "\" class=\"products grid_3\"><a href=\"";
$div3 = "\"><h3 class=\"name\">";
$hero_img = "</h3><img class=\"hero\" src=\"_images/heros/";
$li_price = "<ul><li>Price: <span class=\"price\">$";
$li_serves = "<li>Serves: <span class=\"serves\">";
$li_num = "<li>KC# <span class=\"kcnum\">";
$li_close = "</span></li>";
$div4 = "</ul></a></div>";
for ($i = 0; $i < $names_size; $i++) {
$div = $div1 . $names[$i] . $div2 . $img_link . $i . "/0.jpg" . $div3 . ucwords($names[$i]) . $hero_img . $i . ".jpg\" alt=\"" . ucwords($names[$i]) . "\" />";
$div .= $li_price . $prices[$i] . $li_close;
$div .= $li_kc_num . $kc_no[$i] . $li_close;
$div .= $li_serves . $serves[$i] . $li_close;
$div .= $div4;
echo "{$div}" . "\n";
}
The problem I'm having is that before I echo the final $div, I need to add a list of links for the specific product so I can use make the lightbox work for each div. I tried inserting the code (below) just before echoing the completed $div, but I couldn't go any further with it.
$gallery_array = array();
$files = scandir($img_link . $i);
foreach($files as $file) {
array_push($gallery_array, $file);
}
$gallery_array_size = sizeof($gallery_array);
I honestly don't even know if the Lightbox can even work like this. Any ideas?
You don't have to create a $div like that. You can mix php and HTML codes together.
Your $gallery_array is the same as the $files.
<?php
$names = array ('item1', 'item2', 'item3');
$prices = array ('item1', 'item2', 'item3');
$kc_no = array ('item1', 'item2', 'item3');
$serves = array ('item1', 'item2', 'item3');
$names_size = sizeof($names);
$img_link = "_images/products/";
for ($i = 0; $i < $names_size; $i++) {
?>
<div id="<?=$names[$i]?>" class="products grid_3">
<a href="<?=$img_link.$i?>/0.jpg">
<h3 class="name"><?=ucwords($names[$i])?></h3>
<img class="hero" src="_images/heros/<?=$i?>.jpg" alt="<?=ucwords($names[$i])?>" />
<ul>
<li>Price: <span class="price">$<?=$prices[$i]?></span></li>
<li>KC# <span class="kcnum"><?=$kc_no[$i]?></span></li>
<li>Serves: <span class="serves"><?=$serves[$i]?></span></li>
</ul>
<span>Gallery</span>
<ul>
<?php
$files = scandir($img_link . $i);
for ($x = 2; $x < sizeof($files); $x++) {
echo "<li>".$files[$x]."</li>";
}
?>
</ul>
</a>
</div>
<?php
}
?>

Showing a variable more than once depending on another variable (SQL)

I want to show a variable (which is an image) a certain amount of times depending on the number from a different column.
So I want to have $image shown $numberofratings times (which is up to 5). I'm pretty new to SQL, so I'm probably missing something quite basic, but thankyou to anyone who helps!
<?
$query = mysql_query("SELECT * FROM alex_demo23");
while ($row = mysql_fetch_array($query)){
$rating=$row['rating'];
$numberofratings=$row['numberofratings'];
$image = '<img src="images/star.png">';
echo ("addMarker(Rated: $rating $image from $numberofratings reviews');\n");
}
?>
Just use a for() or a str_repeat:
$image = '';
for($i=0; $i<$numberofratings; $i++){
$image .= '<img src="images/star.png">';
}
Or
$image = str_repeat('<img src="images/star.png">', $numberofratings);
This should do it:
$image = "";
for ($i = 0; $i < $row['numberofratings']; $i++) {
$image .= '<img src="images/star.png">';
}
There's no error checking to make sure that the data is valid, but it should be a start.

how to display only 5 records?

What i want to do is read rssfeed, so I already did it, but I display as foreach loop, so how can I only display 5 records ? now I get more than 10 records, but I only need top 5 records, Isn't anyway php, javascript or jquery make it only show 5 records?
here is my code to read the rss file:
function getrssFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry) {
echo "<li><a href = '$entry->link' title='$entry->title'><h3>" . $entry->title . "</h3></a>" . $entry->pubDate . "<br /><br />" . strip_tags($entry->description) . "</li>";
}
echo "</ul>"; }
getrssFeed("http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss");
thank you
the easiest way would be to stop your loop after 5 iterations:
$i = 0;
foreach($x->channel->item as $entry) {
// do something
$i++;
if($i==5){
break;
}
}
another (more beautiful) way would be to use a for-loop instead of foreach:
for($i=0; $i<=min(5, count($x->channel->item)); $i++) {
$entry = $x->channel->item[$i];
// do something
}
EDIT :
thanks to Juhana, i changed the code to take that into account.
Try putting a counter in your foreach loop with an if statement to check when the counter is over 5. If the counter is under 5 -> display RSS post, counter++. Else -> Exit loop.
Why not use a simple for loop instead?
for($i = 0, $i <= 5, $i++) {
echo "<li><a href = '$x->channel->item[$i]->link' title='$x->channel->item[$i]->title'><h3>" . $x->channel->item[$i]->title . " </h3></a>" . $x->channel->item[$i]->pubDate . "<br /><br />" . strip_tags$x->channel->item[$i]->description) . "</li>";
}
You can use jQuery feed Plugin.
$('div.feed').Feed({
count:5;
});
<div class="feed" link="http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss" ></div>
Feeds would be loaded to container feed.

Problem with numbers and nonexistence

So I have a script that includes forms that are stored in files named like 0101, 0102, and the next category would be 0201, 0202, 0203. The first two set of numbers are the category, second set are the pages in for the forms.
The problem I am having with this numbering is that I am storing the number as 0101 or 0205 and since the first number is only a non-existent thing, 0, it seems to be knocking it off. The only way I managed to actually make it work in some messy way was to do something like this:
"planpages/0" . $nextcat . ".php"
Where $nextcat might be 203. It doesn't seem to like the 0 in front of anything, and must be stored in a string which has something before it (in the case above, you have a "/" sign).
How do I solve the problem with data loss? I did try looking it up in other places, but I didn't know what to put in for the query.
EDIT: More code.
The number is originally stored in $_GET['content'], passed to nextForm($current).
function nextForm($current) {
$next = $current[0] . $current[1] . $current[2] . $current[3] + 1;
$nextcat = $current[0] . $current[1] + 1 . 0 . 1;
if(file_exists("planpages/0" . $next . ".php")) {
return "0" . $next;
} elseif(file_exists("planpages/0" . $nextcat . ".php")) {
return "0" . $nextcat;
} else {
return $current;
}
}
Hopefully that is more information needed. It looks like a mess because I tried my hardest to keep those zeros, but they keep disappearing.
You can zero-pad with sprintf:
$form = 1;
$page = 2;
$string = sprintf('%02d%02d', $form, $page);
This will give you:
$string = '0102';
Or if you have:
$value = 102;
Then:
$string = sprintf('%04d', $value);
Maybe you should use str_pad to zero-pad category and page.
$category = 2;
$pages = 1;
$cat = str_pad($category, 2, "0", STR_PAD_LEFT);
$pag = str_pad($pages, 2, "0", STR_PAD_LEFT);
$filename = $cat . $pag;
// $filename = "0201"

Categories