Trouble storing data for a small game - php

Ok so im having trouble with a project im working on. Its going minesweeper in php but in the bases of the game I can't get the different cell blocks to store their information. Ive tried using session and get, but i can't seem to figure out how to store the information or where to put the code. Below is the basic game code: any ideas?
updated: I really appreciate the help I've been trying to tackle this for awhile now. I am unsure of where to place some of the session values. This does not look right to me:
<html>
<body>
<?php
// ~~~~~~~~~ VARIABLES ~~~~~~~~~~
session_start();
$_SESSION[$piece] = $piece;
$default_board = "default_board";
$filename = "currentproject.php";
$width = "20px";
$height = "20px";
$y_coord = 50;
$how_many_spots = 25;
echo "<table border=1>";
$_SESSION['clicks'] = array();
for ($y=24;$y!=0;--$y) {
$y_coord += $height;
$x_coord = 50;
for ($x=24;$x!=0;--$x){
$x_coord += $width; $cell_sum = $x + $y; $remainder = $cell_sum%2; // some math
if (isset($piece[$x][$y])) {
$background_color = "#991122"; //shows a mine
} else if ($remainder == 0) {
$background_color = "#CCCCCC";
} else $background_color = "#AAAAAA";
echo "<div onclick=\"javascript:document.location.href='$filename?xcord=$x&ycord=$y';\" style=\"border: 1px solid black; background-color: $background_color; position: absolute;left: $x_coord; top: $y_coord; width: $width; height: $height;\">";
echo "</div>";
$_SESSION['clicks'][$xcord][$ycord] = False;
$_SESSION['clicks'][$_GET['xcord']][$_GET['ycord']] = True;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MINES GO HERE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while ($how_many_spots!=0){
$i = rand(1,24);
$e = rand(1,24);
if (!isset($piece[$i][$e])){
$piece[$i][$e] = "mine";
--$how_many_spots;
}
}
}
print ("<br>");
}
$_GET['xcord'] = $xcord;
$_GET['ycord'] = $ycord;
?>
</body>
</html>

It could be done using the $_SESSION and $_GET variables. Following is a working example. It was fun to work out and I hope it helps. Note that the code for alternating grey boxes is not quite right and I did not fix it. I also added options for grid size and number of mines as playing with a 25 x 25 grid gave 625 boxes with 25 mines - a rather difficult chance of survival. I defaulted the grid to 4x4 with 1 mine (I like winning) and you can of course change that.
<html>
<head>
<script type="text/javascript">
function gameover($won){
if ($won){
alert("Game Over - You won");
}
else {
alert("Game Over - You lost");
}
}
</script>
</head>
<?php
session_start();
$filename = $_SERVER['PHP_SELF'];
$gridsize = 4;
$nummines = 1;
if (isset($_SESSION['piece'])){
// board has been set up previously - game in progress
if (isset($_GET['new_game'])){
// start a new game
unset($_SESSION['piece']);
}
}
if (isset($_SESSION['grid_size'])){
// game in progress
$gridsize = $_SESSION['grid_size'];
$nummines = $_SESSION['num_mines'];
}
if (isset($_GET['grid_size'])){
// New Game - set from form choice
$gridsize = $_GET['grid_size'];
$nummines = $_GET['num_mines'];
$_SESSION['grid_size'] = $gridsize;
$_SESSION['num_mines'] = $nummines;
}
?>
<body>
<div>
<form name="minesweeper" action="<?php echo $filename ?>" method="GET">
Enter Grid Size: <input type="input" value="<?php echo $gridsize ?>" name="grid size">
Enter Number of Mines: <input type="input" value="<?php echo $nummines ?>" name="num_mines">
<input type="submit" value="New Game" name="new_game">
</form>
</div>
<?php
// ~~~~~~~~~ VARIABLES ~~~~~~~~~~
$default_board = "default_board";
$width = "20px";
$height = "20px";
$y_coord = 50;
$how_many_spots = $gridsize;
echo "<table border=1>";
if (isset($_SESSION['piece'])){
// board has been set up previously - game in progress
if (isset($_GET['x'])){
// if cell clicked
if ($_SESSION['piece'][$_GET['x']][$_GET['y']] == "mine"){
// if mine - game over
$game_over = true;
$_SESSION['piece'][$_GET['x']][$_GET['y']] = "explode";
}
else {
// mark clicked
$_SESSION['piece'][$_GET['x']][$_GET['y']] = "clicked";
}
}
// draw board
$clickcounter = 0;
for ($y=$gridsize;$y!=0;--$y) {
$y_coord += $height;
$x_coord = 50;
for ($x=$gridsize;$x!=0;--$x){
$x_coord += $width; $cell_sum = $x + $y; $remainder = $cell_sum%2; // some math
if ($_SESSION['piece'][$x][$y] === "explode") {
$background_color = "Black";
$game_over = true;
}
elseif ($_SESSION['piece'][$x][$y] === "clicked") {
// clicked
$background_color = "Green";
$clickcounter++;
}
elseif ($_SESSION['piece'][$x][$y] === "mine" && isset($game_over)) {
//shows all mines when game over
$background_color = "#991122";
}
elseif ($remainder == 0) {
$background_color = "#CCCCCC";
}
else {
$background_color = "#AAAAAA";
}
echo "<div onclick=\"javascript:document.location.href='$filename?x=$x&y=$y';\" style=\"border: 1px solid black; background-color: $background_color; position: absolute;left: $x_coord; top: $y_coord; width: $width; height: $height;\">";
echo "</div>";
}
}
if (isset($game_over)){
echo "<script language='JavaScript'>gameover(false)</script>";
}
elseif ($clickcounter >= ($gridsize * $gridsize) - $nummines){
echo "<script language='JavaScript'>gameover(true)</script>";
}
}
else{
for ($y=$gridsize;$y!=0;--$y) {
$y_coord += $height;
$x_coord = 50;
for ($x=$gridsize;$x!=0;--$x){
$x_coord += $width; $cell_sum = $x + $y; $remainder = $cell_sum%2; // some math
// shows a mine for debugging
if (isset($_SESSION['piece'][$x][$y]) && $_SESSION['piece'][$x][$y]=="mine") {
if ($remainder == 0){
$background_color = "#CCCCCC";
}
else {
$background_color = "#AAAAAA";
}
}
elseif ($remainder == 0) {
$_SESSION['piece'][$x][$y] = false;
$background_color = "#CCCCCC";
}
else {
$_SESSION['piece'][$x][$y] = false;
$background_color = "#AAAAAA";
}
echo "<div onclick=\"javascript:document.location.href='$filename?x=$x&y=$y';\" style=\"border: 1px solid black; background-color: $background_color; position: absolute;left: $x_coord; top: $y_coord; width: $width; height: $height;\">";
echo "</div>";
// ~~~~~~~~~MINES GO HERE ~~~~~
while ($nummines!=0){
$i = rand(1,$gridsize);
$e = rand(1,$gridsize);
$_SESSION['piece'][$i][$e] = "mine";
--$nummines;
}
}
print ("<br>");
}
}
?>
</body>
</html>

Related

How to implement pagination using CSV and PHP [duplicate]

I have a small script that displays blog posts from a text file, how can I add pagination so that it only shows 5 blog posts at a time?
Here is the script:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
$fp = fopen($opFile,"r") or die("Error Reading File");
$data = fread($fp, filesize($opFile));
fclose($fp);
$line = explode("\n", $data);
$i=count($line);
for ($n=0 ; $n < $i-1 ; $n++ ) {
$blog = explode("|", $line[$n]);
if (isset($blog[0]))
{
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
}
?>
</body>
</html>
And here is the text file:
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Any help is greatly appreciated!
Something like this:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$POSTS_PER_PAGE = 10;
//Not sure what this is for, but I left it?
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
//Explode the textfile into lines
$lines = file($opFile);
$posts = array();
foreach($lines as $line) {
//Ignore blank lines
if($line != "") {
//Explode each non-empty line
$post = explode("|", $line);
//Store the blog post
array_push($posts, $post)
}
}
//Output the pagination links
echo "<div class=\"blog-pagination\">";
for($i = 1; $i < ceil(count($posts) / $POSTS_PER_PAGE; $i++) {
echo '' + $i + ' ';
}
echo "</div>";
//Assume the user wants the first page if it's not specified
if(!isset($_GET['page'])) {
$_GET['page'] = 1;
}
//Figure out the first and last posts on this page
$first_post = ($_GET['page'] - 1) * $POSTS_PER_PAGE;
$last_post = $_GET['page'] * $POSTS_PER_PAGE - 1;
//Display the requested posts
for($i = $first_post; $i <= $last_post; $i++) {
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
?>
(This is completely untested, but hopefully you can take it from here!)
This worked in my tests:
define('MAX_PER_PAGE',10);
// sanity checks for per-page and page index
$numPosts = ctype_digit((string)$_GET['perpage']) ? $_GET['perpage'] : 5;
$ostart = $start = max(1, ctype_digit((string)$_GET['page']) ? $_GET['page'] : 1) - 1;
$mode = 0;
if ($mode == 0) {
$file = "blogfile.txt";
}
// read the file into an array, strip newlines and ignore empty lines
file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);
// sort array (see custom function at bottom)
usort($line, 'blogsort');
$lines = count($line);
// get total number of pages
$numPages = ceil($lines / $numPosts);
// additional sanity checks (also sets $ostart if it was invalid; used later)
$numPosts = min(MAX_PER_PAGE, max(1, $numPosts));
if ($start * $numPosts > $lines ) {
$ostart = $start = max(0, $lines - $numPosts);
}
else {
$start *= $numPosts;
}
// Only grab the part of the array we need
$sliced = array_slice($line, $start, $numPosts);
// loop through posts, but break early if we run out
for ($n = 0; $n < $numPosts && isset($sliced[$n]); $n++ ) {
$blog = explode("|", $sliced[$n]);
if (isset($blog[0])) {
echo "<div class=\"blog-post\">\n",
"<p class=\"blog-title\">{$blog[1]}</p>\n",
"<p class=\"blog-message\">{$blog[2]}</p>\n",
"<p class=\"blog-date\">Posted: {$blog[0]}</p>\n",
"<div style=\"clear: both;\"></div>\n",
"</div>\n\n";
}
}
// back link
if ($ostart > 0) {
echo "← Older";
}
else {
echo "None Older";
}
echo " || ";
// forward link
if ($ostart + 1 < $numPages) {
$next = $ostart + 2;
echo "Newer →";
}
else {
echo "None Newer";
}
function blogsort($a, $b) {
$dateA = strtotime(substr($a, 0, strpos($a, '|')));
$dateB = strtotime(substr($b, 0, strpos($b, '|')));
if ($dateA == $dateB) {
return 0;
}
elseif ($dateA > $dateB) {
return -1;
}
else {
return 1;
}
}

Increment number in php every time data is received from sql

I am trying to make a program that can get data from Sql using php. the received data is a number from 1 to 5 and each number presents a color. every time a number is received a counter adds 1 for that color in html. I have been able to code this but if the page is refreshed the counted value becomes 0.
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['name'].", ".$row['color']";
$red = "5";
$pink = "4";
$yellow = "3";
$black = "2";
$white = "1";
$colorid = $row['color'];
if ($colorid == $red){
echo "Red";
$re = 1;
$re = ++;
} elseif ($colorid == $pink){
echo "Pink";
$pi = 1;
$pi = ++;
} elseif ($colorid == $yellow){
echo "Yellow";
$ye = 1;
$ye = ++$;
} elseif ($colorid == $black){
echo "Black";
$blk = 1;
$blk = ++;
} elseif ($colorid == $white){
echo "White";
$wh = 1;
$wh = ++;
} else {
echo "Cannot verify the color code";
}
}
?>
<div>
<span>White: </span><input name="white" value="<?php echo (isset($wh))?$wh:'';?>">
<span>Black: </span><input name="black" value="<?php echo (isset($blk))?$blk:'';?>">
<span>Yellow: </span><input name="yellow" value="<?php echo (isset($ye))?$ye:'';?>">
<span>Pink: </span><input name="pink" value="<?php echo (isset($pi))?$pi:'';?>">
<span>Red : </span><input name="red" value="<?php echo (isset($re))?$re:'';?>">
</div>

How to filter or find in AJAX callback results from PHP listing files from directory

Trying to display all photos from a directory in a div.
Looking to show all portraits first, then squares, then landscapes last.
Will align and style later, but first I just need a point in the right direction on how to sort the results of a callback.
do1.php
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['showphotos'])) {
$af = glob("main/photos/*.*");
for ($i=0; $i<16; $i++) {
$iname = $af[$i];
$supported_format = array('gif','jpg','jpeg','png','mp4');
$ext = strtolower(pathinfo($iname, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format)) {
list($width, $height) = getimagesize($iname);
if( $height / $width > 1.15) {
$ori = "p";
} elseif( $width / $height > 1.15) {
$ori = "l";
} elseif( $height / $width < 1.15) {
$ori = "s";
} elseif( $width / $height < 1.15) {
$ori = "s";
}
echo "<img class='".$ori.":' title='".$ori.$iname."' src='".$iname."' alt='".$iname."' height='300px' />";
} else {
die("something went terribly wrong you ditz!");
}
}
exit;
}
The above gets all the files, determines whether portrait/landscape/square, and sets a className of s, l, or c.
Script on Index.php
$(document).ready(function(){
$("#galphoto").click(function(){
$("#chme").children().hide(2000, function() {
$("#supics").delay(2000).slideDown(2000);
var id1 = 1;
$.ajax({
url:'do1.php',
type:'POST',
data:{showphotos: id1},
success: function(pics){
$('#supics').html(pics);
}
});
});
});
});
Of course this puts all of the images into the div.
I thought I could filter them somehow by assigning each image a class name based on there orientation, but after many trials and errors I haven't succeeded.
I know there must be some simple thing like attr('.p') or something. If this question is a duplicate please point me to the correct page. Thanks for any help.
Instead of outputting the result directly, place the results of your orientation check into one of 3 arrays.
Then loop over those arrays outputting what you want, you will also be able to change the attributes to fit the orientation this way.
$port = [];
$land = [];
$sqar = [];
$supported_format = array('gif','jpg','jpeg','png','mp4');
$files = glob("main/photos/*.*");
foreach ($files as $file) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format)) {
list($width, $height) = getimagesize($iname);
if( $height / $width > 1.15) {
$port[] = $file;
} elseif( $width / $height > 1.15) {
$land = $file;
} elseif( $height / $width < 1.15) {
$sqar[] = $file;
} elseif( $width / $height < 1.15) {
$sqar[] = $file;
}
}
}
$htm = '';
foreach ($port as $file) {
$htm .= "<img class='port' title='p$file' src='$file' alt='$file' height='300px' />";
}
foreach ($sqar as $file) {
$htm .= "<img class='sqar' title='s$file' src='$file' alt='$file' height='300px' />";
}
foreach ($land as $file) {
$htm .= "<img class='land' title='l$file' src='$file' alt='$file' height='300px' />";
}
echo $htm;
And this is the jQuery Solution !
var classes = $('img').map(function() {
return $(this).attr('class');
});
var sortedArray = classes.sort();
var uniqueClasses = $.unique(sortedArray);
$(uniqueClasses).each(function(i, v)
{
$('.'+v).wrapAll('<div class ="orientation-'+v+'"></div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="l" title="$ori.$iname" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Stanis%C5%82aw_Mas%C5%82owski_%281853-1926%29%2C_Autumn_landscape_in_Rybiniszki%2C_1902.jpeg/220px-Stanis%C5%82aw_Mas%C5%82owski_%281853-1926%29%2C_Autumn_landscape_in_Rybiniszki%2C_1902.jpeg" alt="$iname" height='300px' />
<img class="p" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Reproduction-of-the-1805-Rembrandt-Peale-painting-of-Thomas-Jefferson-New-York-Historical-Society_1.jpg/170px-Reproduction-of-the-1805-Rembrandt-Peale-painting-of-Thomas-Jefferson-New-York-Historical-Society_1.jpg" alt="$iname" height='300px' />
<img class="l" src="https://upload.wikimedia.org/wikipedia/commons/5/50/1172_ruwenzori.jpg" alt="$iname" height='300px' />
<img class="c" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Regular_polygon_4_annotated.svg/1200px-Regular_polygon_4_annotated.svg.png" alt="$iname" height='300px' />
<img class="l" title="$ori.$iname" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Stourhead_garden.jpg/220px-Stourhead_garden.jpg" alt="$iname" height='300px' />
To achieve the results I needed to use .load instead of an ajax call.
First I edited do1.php by taking out the if($_SERVER["REQUEST_METHOD"]... and then changed the ehco statement to add a unique id.
do1.php
$af = glob("main/photos/*.*");
for ($i=0; $i<24; $i++)
{
$iname = $af[$i];
$supported_format = array('gif','jpg','jpeg','png','mp4');
$ext = strtolower(pathinfo($iname, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
list($width, $height) = getimagesize($iname);
if( $height / $width > 1.33) {$ori = "p";}
elseif( $width / $height > 1.33) {$ori = "l";}
elseif( $height / $width < 1.33) {$ori = "s";}
elseif( $width / $height < 1.33) {$ori = "s";}
}
echo "<img id='i".$i."' class='".$ori."' src='".$iname."' alt='".$iname."' height='280px' />";
}
So now the page does not need to be AJAX, called just loaded. Also; Each image is assigned a unique id id='i0', id='i1', id='i2'..., and each element has an assigned class based on it's orientation (portrait=p, landscape=l, square=s).
Next I added three span elements (#c1, #c2, #c3) into the div where I wanted the content to show (#supics).
Next I edited my script to LOAD from do1.php insted of using the AJAX POST.
Script on Index.php
$(document).ready(function(){
$("#galphoto").click(function(){
$("#chme").children().hide(2000, function() {
$("#supics").delay(2000).slideDown(3000);
$("#supics").css({"max-height": "700px", "overflow": "auto"});
var $page = $('<div><div>').load('do1.php .p, .s, .l', //loads elements with classes of p, s, & l from do1.php
function() {
var $p = $page.find('.p'); //finds all class='p' elements & assigns $p as variable to them
var $s = $page.find('.s'); //finds all class='s' elements & assigns $s as variable to them
var $l = $page.find('.l'); //finds all class='l' elements & assigns $l as variable to them
var ipics = [$p, $s, $l]; //putting variables in an array
$('#c1').html(ipics[0]); //puts $p (all class.p elements) into element with id='c1'
$('#c2').html(ipics[1]); //puts $s (all class.s elements) into element with id='c2'
$('#c3').html(ipics[2]); //puts $l (all class.l elements) into element with id='c3'
$(ipics[0]).addClass("fad"); //adds another class to all class.p elements for extra styling
$(ipics[1]).addClass("fid"); //adds another class to all class.s elements for extra styling
$(ipics[2]).addClass("fod"); //adds another class to all class.l elements for extra styling
});
});
});
});
This may be dirty (though I'm no judge at determining that), but it allows me to load everything I need at once, then sort the content, and style it all anyway I need. I hope this helps someone out. Thank you all for the help.

How to inject code in posts after X images in Wordpress

We have a function in Wordpress that show a block of code after 3 paragraphs in posts:
add_filter('the_content', 'wpse_ad_content');
function wpse_ad_content($content)
{
if (!is_single()) return $content;
$paragraphAfter = 3; //Enter number of paragraphs to display ad after.
$content = explode("</p>", $content);
$new_content = '';
for ($i = 0; $i < count($content); $i++) {
if ($i == $paragraphAfter) {
$new_content.= '<div style="col-xs-12">';
$new_content.= 'code here';
$new_content.= '</div>';
}
$new_content.= $content[$i] . "</p>";
}
return $new_content;
}
We are trying to complete this function for include and display another block of code only in post that contains at least 8 images (understanding by image each
<img src=...
).
This block should displayed after the image nº8, if they aren't eight images, the additional function doesn't display nothing.
----- Edit 1:
After trying with the #TimTroiano solution
add_filter('the_content', 'wpse_ad_content');
function wpse_ad_content($content)
{
if (!is_single()) return $content;
$paragraphAfter = 3; //Enter number of paragraphs to display ad after.
$imagesAfter = 7; //Enter number of images to display code snippet after.
$content = explode("</p>", $content);
$new_content = '';
for ($i = 0; $i < count($content); $i++) {
if ($i == $paragraphAfter) {
$new_content.= '<div class="col-lg-12" style="text-align: center; padding-top: 10px; margin-bottom: 20px;">';
$new_content.= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- La nube sobre título -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client=""
data-ad-slot="7588478595"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
$new_content.= '</div>';
}
$new_content.= $content[$i] . "</p>";
if ($imagesAfter > 0) {
$imagesAfter -= 1;
} else {
$new_content.= '<div class="col-lg-12" style="text-align: center; padding-top: 10px; margin-bottom: 20px;">';
$new_content.= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- La_Nube_4_Anuncio -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client=""
data-ad-slot="3663644595"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
$new_content.= '</div>';
$imagesAfter = 7; //Reset number of images to display code after.
}
}
return $new_content;
}
We noticed a strange behavior.
1. Consider the paragraphs of text as if they were pictures .
2. In addition repeats the block of code if more images or paragraphs ( multiples of 8) and should appear only once.
Thank you for posting the relevant code. I added a variable $imagesAfter which will count how many images have been inserted before adding your code snippet. When $imagesAfter reaches 0 it inserts whatever you choose to insert and resets $imagesAfter back to the original number.
What I added:
$imagesAfter = 7; //Enter number of images to display code snippet after.
if ($imagesAfter > 0) {
$imagesAfter -= 1;
} else {
**Code snippet after set number of images goes here**
$imagesAfter = 7; //Reset number of images to display code after.
}
Here is the full code with the part I added in the appropriate places:
function wpse_ad_content($content)
{
if (!is_single()) return $content;
$paragraphAfter = 3; //Enter number of paragraphs to display ad after.
$imagesAfter = 7; //Enter number of images to display code snippet after.
$content = explode("</p>", $content);
$new_content = '';
for ($i = 0; $i < count($content); $i++) {
if ($i == $paragraphAfter) {
$new_content.= '<div style="col-xs-12">';
$new_content.= 'code here';
$new_content.= '</div>';
}
$new_content.= $content[$i] . "</p>";
if ($imagesAfter > 0) {
$imagesAfter -= 1;
} else {
**Code snippet after set number of images goes here**
$imagesAfter = 7; //Reset number of images to display code after.
}
}
return $new_content;
}
Here's an even simpler solution. Use a modulus operator to test if $i is a multiple of 8, then show the image.
$if ($i > 0) {
if ($i % 8 == 0) {
**Code snippet after set number of images goes here**
}
}
This would go here in your code:
function wpse_ad_content($content)
{
if (!is_single()) return $content;
$paragraphAfter = 3; //Enter number of paragraphs to display ad after.
$content = explode("</p>", $content);
$new_content = '';
for ($i = 0; $i < count($content); $i++) {
if ($i == $paragraphAfter) {
$new_content.= '<div style="col-xs-12">';
$new_content.= 'code here';
$new_content.= '</div>';
}
$if ($i > 0) {
if ($i % 8 == 0) {
**Code snippet after set number of images goes here**
}
}
$new_content.= $content[$i] . "</p>";
}
return $new_content;
}
Let me know if this solves your problem or if you were looking for something different.

Generate gallery loop

The Problem
I'm attempting to generate a gallery where it will display 3 "blocks" per row and alternate between large and small images.
For example:
Big | 4 Small | Big
4 Small | Big | 4 Small
One big image is the size of 4 small images.
What I've Tried
Here's an example of what I've tried so far.
$i = 0;
$r = 0;
$image = '';
foreach($gallery_images as $image_data) {
($i == 5 ? $i = 0 : '');
//If there's been 3 blocks added to the row, end the row and start a new one
if($r == 3) { $image .= '</div>'; $r = 0; }
//Start new row every 3 blocks
if($r == 0) { $image .= '<div class="row">'; }
//One big image, per 4 small in sequence
if($i == 0) {
$image .= '<div style="height: 300px; width:33.3%; background: red;float:left;"></div>';
++$r;
} else {
//If no small, start the block
if($i == 1) { $image .= '<div style="width:33.3%;height:300px;float:left;">'; }
//echo each small image
$image .= '<div style="height: 150px; width:50%;background: blue;float:left;"></div>';
//Once 4 images have been echoed, close the div
if($i == 4) { $image .= '</div>'; ++$r; }
}
++$i;
}
echo $image;
The first row displays fine, but then the next row messes up completely. I just can't see what I've missed in order for this to work.
The class of "row" is because I'm building this upon the foundation framework by Zurb in order to make it responsive.
The issue is that on the 2nd row(s), you do not increment $r to 1 until the end of the 4 small, so it continues to add <div class="row"> before each small image. You need to change your if block on the even rows. You can do this by adding 1 more counter, that keeps track of what row you are on -
by adding
$t=0;
and changing
//Start new row every 3 blocks
if($r == 0) { $image .= '<div class="row">'; }
to
//Start new row every 3 blocks
if($t%2==1){ // if we are on an even row
if($i == 1 && $r == 0) { $image .= '<div class="row">';}
}
else{ // if we are on an odd row
if($r == 0) { $image .= '<div class="row">'; }
}
you now have-
$i = 0;
$r = 0;
$image = '';
$t=0; // counter for odd/even row
foreach($gallery_images as $image_data) {
($i == 5 ? $i = 0 : '');
//If there's been 3 blocks added to the row, end the row and start a new one
if($r == 3) { $image .= '</div>'; $r = 0; ++$t; }
//Start new row every 3 blocks
if($t%2==1){ // if we are on an even row
if($i == 1 && $r == 0) { $image .= '<div class="row">';} // if it is the first small image group start the row
}
else{ // if we are on an odd row
if($r == 0) { $image .= '<div class="row">'; } // if it is the first large image
}
//One big image, per 4 small in sequence
if($i == 0) {
$image .= '<div style="height: 300px; width:33.3%; background: red;float:left;"></div>';
++$r;
} else {
//If no small, start the block
if($i == 1) { $image .= '<div style="width:33.3%;height:300px;float:left;">'; }
//echo each small image
$image .= '<div style="height: 150px; width:50%;background: blue;float:left;"></div>';
//Once 4 images have been echoed, close the div
if($i == 4) { $image .= '</div>'; ++$r; }
}
++$i;
}
echo $image;
you can see a phpFiddle example at http://phpfiddle.org/main/code/t25-kbe This is with 60 images, so there is 4 rows total, 2 of each pattern.
NEW ANSWER:
Ok this is how you wanted it:
<style type="text/css">
.big {
width:200px;
height:200px;
background:#03F;
}
.small {
width:50px;
height:50px;
background:#F00;
}
</style>
<?
$gallery_images = array(
1,2,3,4,5,6
);
echo '<div class="row">';
//count counts whether it's big or small
$count = 0;
//count2 counts whether it's the end of the row or not
$count2 = 0;
$row = 0;
foreach($gallery_images as $image_data) {
//assign these from image data
$big = "<img class='big'>";
$small = array(
"<img class='small'>","<img class='small'>","<img class='small'>","<img class='small'>"
);
//if it's 0 it's big else it's 1 and it's small
if($count === 0) {
echo $big;
$count++;
}else {
foreach($small as $s) {
echo $s;
};
$count = 0;
}
//if it's 2 then its the end of the row else increment
if($count2 === 2) {
echo "</div>";
echo "<div class='row'>";
$count2 = 0;
}else {
$count2 ++;
}
}
?>
NEW:
Ok you'd need to tinker with this, but I think it solves the issue:
<style type="text/css">
.big {
width:200px;
height:200px;
background:#03F;
}
.small {
width:50px;
height:50px;
background:#F00;
}
</style>
<?
$gallery_images = array(
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
);
//find out how many images
$total_images = count($gallery_images);
echo '<div class="row">';
//count counts whether it's big or small
$count = 0;
//count2 counts whether it's the end of the row or not
$count2 = 0;
$row = 0;
//overall count of images
$overall = 0;
for($i=0;$i<count($gallery_images);$i++) {
//assign these from image data
$big = "<img class='big' src='".$gallery_images[$i]."'>";
//increment overall
$overall++;
if($i+1 < $total_images) {
$small1 = $i+1;
$small[] = $small1; //would be $gallery_images[$small1]
$overall++;
}
if($i+1 < $total_images) {
$small2 = $i+2;
$small[] = $small2; //would be $gallery_images[$small2]
$overall++;
}
if($i+1 < $total_images) {
$small3 = $i+3;
$small[] = $small3; //would be $gallery_images[$small3]
$overall++;
}
if($i+1 < $total_images) {
$small4 = $i+4;
$small[] = $small4; //would be $gallery_images[$small4]
$overall++;
}
//if it's 0 it's big else it's 1 and it's small
if($count === 0) {
if($overall < $total_images) {
echo $big;
$count++;
}
}else {
if($small) {
foreach($small as $s) {
echo "<img class='small' src='".$s."' />";
};
$count = 0;
}
}
if($count2 === 2) {
echo "</div>";
echo "<div class='row'>";
$count2 = 0;
}else {
$count2 ++;
}
unset($small);
if($overall >= $total_images) {
echo "</div>";
}
}
?>

Categories