I am adding in feed Ads to my website. I have a foreach statement that creates a list of posts. I have created a counter that is supposed to count every four posts and insert the Ad content then repeat.
I have tried some other iterations of this but this is the one I can actually get to do something. I can find a lot of info on this exact thing pertaining to wordpress. But I am running cake php and would prefer a pure php solution.
<?php
$count = 1;
foreach($stories as $story) {
echo '<h2>'.$story->title.'</h2>';
if(!empty($story->excerpt)) {
echo $story->excerpt;
} else {
echo limit_text($story->body);
}
if ($count % 4 == 1) {
echo AD_SENSE_INFEED;
}
}
$count++;
?>
This code is what I currently have but its not working the way I would like it to. As if now it basically goes every other. So POST, AD, POST AD...etc.
Your problem isn't a coding problem, its a math problem. What you're using is called modulos or remainders basically.
So that said:
if ($count % 4 == 1) {
For it to equal 1 we have to feed in something that goes in evenly once and leaves one more.
What you want to do is:
if ($count % 4 == 0) {
Aka it means there's no remainder, 4 goes into it evenly with nothing left over.
As #RiggsFolly mentioned and I completely missed this(Give his comment a up vote) your $count variable should be incremented inside the loop as well otherwise it will only increment once after the loop ends.
You can get rid of count all together (and just use the numeric index of the array)
//just some "test" data
$stories = array_fill(0, 100, []);
foreach( $stories as $count => $story) {
echo $count." ".($count % 4)."\n";
if ($count % 4 == 3) {
echo "--------------------------------------\n";
}
}
Output:
0 0
1 1
2 2
3 3
--------------------------------------
4 0
5 1
6 2
7 3
--------------------------------------
...
Sandbox
If your not sure if the keys are in proper order, you can reset them:
foreach(array_values($stories) as $count => $story) {
Obviously an array starts at 0, so you have to offset the % result a bit ... lol ... Yes I am to lazy to increment.
Related
I have this array, I want to make conditional action based on the items hierarchy in the array. I'm going to compare between items based on their hierarchy and it will result a 2 dimensional array like this.
The comparison is : Imagine that there are 3 stair, in the highest stair is 5, the second stair is 3 and the last stair is 1.
If a number compared with the 1st lower floor then it'll be 3 and if a number compared with the 2nd lower floor then it'll be 5. Example : if 5 is compared with 3 then it'll be 3, if 5 is compared with 1 then it'll be 5. If a number compared with the 1st upper floor then it'll be 1/3 and if a number compared with the 2nd upper floor then it'll be 1/5. Example if 1 is compared with 3 then it'll be 1/3 and if 1 is compared with 5 then it'll be 1/5. And if 3 is compared with 5 then it'll be 1/3 and if 3 is compared with 1 then it'll be 3.
So far, this is my code
$weightvalue = array(5,3,1);
$numbers = count($weightvalue);
for ($row = 0; $row < $numbers; $row++) {
for ($column = 0; $column < $numbers; $column++) {
echo "$weightvalue[$row],$weightvalue[$column] ";
if ($weightvalue[$row]==$weightvalue[$column]) {echo "1";}
elseif ($weightvalue[$row]<$weightvalue[$column]) {echo "1/3";}
elseif ($weightvalue[$row]<$weightvalue[$column]) {echo "1/5";}
elseif ($weightvalue[$row]>$weightvalue[$column]) {echo "3";}
elseif ($weightvalue[$row]>$weightvalue[$column]) {echo "5";}
else {echo "false";};
echo ("\n");
}
}
So far this is the result, but there're some mistakes, I know what causes this but I don't know how to fix it. Please help, any suggestion will very much appreciated.
PHP is an alien language for me. I am trying to pull some fields from WP's SQL database.. The content comes out okay but is a lot. I want to somehow put it in a HTML carousel or some slider, where data must be formatted like this:
<holder1>
<data1></data1>
<data2></data2>
<data3></data3>
</holder1>
<holder2>
<data4></data4>
<data5></data5>
<data6></data6>
</holder2>
I imagine I would have to put some for loop for i<4, do, then break into holder2.
Current script that echos the data =
while($row = mysql_fetch_array($rs)) {
echo "<div class='testimonials flexslider'><ul class='slides'><li class='testimonial flex-active-slide'><blockquote><p>" . $row['post_content'] . "</p><cite><span>" . $row['post_title'] . "</cite></span></blockquote></li></ul></div>"; }
I would like it to break after 3 <li> items each, into a seperate <div> or <article> whatever I find suitable according to the carousel I use.
You need an index variable, which echoes the beginning of the wrapper when it is divisible by 3, and the end of the wrapper when it leaves a remainder of 2 after division by 3 (and at the very end). It seems like this code would work:
$index = 0;
while($row = mysql_fetch_array($rs)) {
if ($index % 3 == 0) {
echo "<div class='testimonials flexslider'><ul class='slides'>";
}
echo "<li class='testimonial flex-active-slide'><blockquote><p>" . $row['post_content'] . "</p><cite><span>" . $row['post_title'] . "</cite></span></blockquote></li>";
if ($index % 3 == 2) {
echo "</ul></div>";
}
$index++;
}
if ($index % 3 != 2) {
echo "</ul></div>";
}
EDIT: a little bit of explanation to clarify the math. Suppose you have 10 results. Because we usually count from 0 in programming, they can be numbered 0 up to 9. This would make your structure look like this:
<holder>
<data0></data0>
<data1></data1>
<data2></data2>
</holder>
<holder>
<data3></data3>
<data4></data4>
<data5></data5>
</holder>
<holder>
<data6></data6>
<data7></data7>
<data8></data8>
</holder>
<holder>
<data9></data9>
</holder>
You see that we need a <holder> before elements 0, 3, 6 and 9 - all numbers which are divisible by 3. Mathematically, this is expressed with help of the remainder function - a number is divisible by 3 when its remainder after dividing by 3 is zero.
Likewise, we need a </holder> after elements 2, 5 and 8 - numbers which after division by 3 leave a remainder of 2.
We need to take care of the situation where the last block is not complete; that's why there's an extra block of code to take care of the last </holder>.
When I say 'Every 3rd Iteration' I mean 'Every 3rd Iteration... starting from number 4'
If it were just every 3rd, I would target the appropriate iterations like so:
<?php if ($count % 3 == 0) : ?>
Bear in mind I've set $count to 1 beforehand
But the iterations need to start with the 4th, then 7th, 10th etc.
Does anyone know how I can acheive this? Can I do it with a simple if statement like the one above?
Unfortunately I don't think a for loop will be possible as this is a WordPress loop I'm dealing with
Your thoughts about using the modulus operator are sound, you just need to expand the scope of your logic surrounding it:
You want every third iteration after the initial 4 have passed. Begin your logic after the first 4:
if ($count > 4)
Then, you want each 3 after that. Your counter includes the initial 4 iterations you didn't want to include, so remove that from your counter and check if the current iteration is a multiple of 3:
if (($count - 4) % 3 === 0)
This should give you what you're looking for.
if ($count > 4)
{
if (($count - 4) % 3 === 0)
{
...
}
}
You can also put this into one line:
if ($count > 4 && ($count - 4) % 3 === 0)
{
...
}
foreach($array as $key=>$value){
if($key % 3 != 0){
continue;
}
}
I have this difficult task (for me at least).
This is abstract question, mathematical i'd say.
Let's assume I have 2 inputs:
a keyword (string)
a number (deepness level)
and submit button.
This keyword returns me 8 other keywords from a database that are similar to this string.
And for each of that 8 keywords I need to call same function that will return me another 8 similar keywords of all these 8 strings I have already returned.
Here comes the "level" number. I need to go deeper inside every of returned string depending on level number I entered.
For example: If the level number is 2, then we will call the function 9 times. First time for the original keyword, and 8 times for each returned keyword.
If the level number is 3, then the function will be called 73 times. Like in the previous example, but plus for another 8 keywords we have returned. I think there will be a couple of loops inside loops, but can't figure it out by myself. Will appreciate your suggestions.
Here's the main code that I have wrote which is probably unsufficient:
$keywords = preg_split('/$\R?^/m', trim($_POST['keyword']));
$keywords = array_map('trim', $keywords);
$level = $_POST['level'];
if (!$level || $level < 2) {
echo '<b>Level was either 1 or null</b>';
}
foreach ($keywords as $keyword) {
$results = getResults($keyword);
if ($level && $results) {
for ($i = 0; $i < sizeof($results); $i++) {
$results1 = getResults($results[$i]);
for ($j = 0; $j < $level; $j++) {
$results1 = getResults($results1[$i])
}
}
}
}
The output should be something like this:
1->
2
->
3
3
3
3
3
3
3
3
2->
2->
2->
2->
You need to understand what recursion means and how you can use it in your code. Basically you need to call the same function inside itself, n times where n is the deepness level of your request.
Start with some little examples like Fibonacci series, and you will find the way to implement your function.
All is based on a condition ($deepness > 0).
Here's a little suggestion (in pseudocode) based on what I understood.
function findSimilar($words,$deepness) {
if($deepness == 0) {
return similarWordsOf($words);
} else {
return similarWordsOf(findSimilar($words,$deepness -1));
}
}
As others have already pointed out, the key to the solution is to use a recursive function, i.e. a function that calls itself again for each of the similar words using a decreased deepness value.
My PHP is a bit rusty, so here's some pseudo code (aka Python):
def printSimilar(word, deepness=1, indent=0):
print (" " * indent) + word
if deepness > 0:
for similar in similarWords(word):
printSimilar(similar, deepness - 1, indent + 1)
Assuming that similarWords returns the list of similar words, this should result in the desired output.
I have this logic written that loops out an array into <li>
and gives #1 and every 5th a class of "alpha".
$count = 0;
foreach($gallery->data as $row){
if ($count==0 || $count%4==0) {
echo '<li class="alpha"></li>'.PHP_EOL;
} else {
echo '<li></li>'.PHP_EOL;
}
$count++;
}
I need to add to this and get the code adding a class of "omega" to every 4th <li>
You do realize that as you describe it, there will be some overlap right? (example - item 30 is both a '5th' and a '6th') Brian gave you an answer for exactly what you described, but I'm not sure if its what you want. You want ALPHA, x, x, x, OMEGA, ALPHA, x, x, x, OMEGA, ALPHA.....
You seem to want Alpha on the 5*k + 1, and Omega on 5*k
conditions:
alpha - ($count + 1) % 5 == 1
omega - ($count + 1) % 5 == 0
I think grouping in the addition makes this easier to understand, since you're count starts at 0 but you seem to be thinking in terms of beginning at 1. If you don't like that, lose the addition and change the equivalences to 0 and 4, respectively - $count % 5 == 0 and $count % 5 == 4
i know this is better suited for a comment under the last answer, but I don't see how. Am i not allowed until my reputation is higher or am i just missing something?>
right now as it stands your code adds the "alpha" class to every fourth item beginning with the first, not every fifth. In other words, items 1, 5, 9, 13, etc. will have a class of "alpha" since your counter begins at 0.
I assume that you want to add the "omega" class then to items 4, 8, 12, etc. Here's what you need to do that:
$count = 0;
foreach($gallery->data as $row){
if ($count%4==0) {
echo '<li class="alpha"></li>'.PHP_EOL;
}
else if ($count%4==3) {
echo '<li class="omega"></li>'.PHP_EOL;
}
else {
echo '<li></li>'.PHP_EOL;
}
$count++;
}