I tested looping nested While statements so:
$count1 = 0;
while ($count1 < 3) {
$count1++;
$count2 = 0;
echo "count1: ".$count1."<br />";
while ($count2 < 3) {
$count2++;
echo "count2: ".$count2."<br />";
}
}
This works perfectly (looping three times each) with results:
count1: 1
count2: 1
count2: 2
count2: 3
count1: 2
count2: 1
count2: 2
count2: 3
count1: 3
count2: 1
count2: 2
count2: 3
Then I tried the same with a loop using mysql_fetch_assoc ($ContactsInterests is a two row associative array, and $LatestNews has 50 rows) i.e.
$CI_count = 0;
while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests
$CI_count++;
$LN_count = 0;
echo "CI_count: ".$CI_count."<br />";
while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news
$LN_count++;
echo "LN_count: ".$LN_count."<br />";
}
}
The results are:
CI_count: 1
LN_count: 1
LN_count: 2
...
LN_count: 50
LN_count: 51
CI_count: 2
But where it the second iteration of LN_count? I don't understand why the LN_count didn't increment a second time.
Help appreciated.
mysql_fetch_assoc does iteration for "mysql result" type. Seeks index for each fetch.
you must use mysql_data_seek to go to the first result like;
<?php
$CI_count = 0;
while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests
$CI_count++;
$LN_count = 0;
echo "CI_count: ".$CI_count."<br />";
mysql_data_seek($LatestNews,0);
while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news
$LN_count++;
echo "LN_count: ".$LN_count."<br />";
}
}
Because the results have been exhausted. You've iterated through all of them... If you wanted to loop again you're have to repopulate the $LatestNews variable.
You need to reset the mysql internal pointer:
see http://php.net/mysql_data_seek
mysql_fetch_assoc() takes out one by one the rows of the source, you when you will be in the second step of the first loop, you wont have any rows in the source variable.
You need to put the results of the second query in an array, then loop the array, and not using mysql_fetch_assoc.
Related
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.
Newbie here, working on their second ever function. I've googles a bit on my problem, looked at PHP.net and at some articles on stack overflow, WC3schools, CoralCode, etc., but i haven't found anything that I can understand as of yet (i've done my diligence before come begging I promise).
The concept of my function is that it will take an array of whatever size, and print it out in rows of four. Function currently returns repeats itself overall equal to the size of the array. So if the array has 8 items, it returns nine groups (groupings defined visually by having the white line between them) of nine items. The first and the last have 16 boxes in them, 2-8 have 32 boxes in them where i was hoping to get back two rows of four with a while line between the two rows
see here for visual error
see here for how it's meant to look
So to sum up, my loop is over iterating/returning too much/not returning the data in the way i hoped. I'm not sure how to phrase the question, but i've done my best to ask it as best I can.
function PrintFolio($aaPlaceholder)
{
//print out two rows of four from array with 8 items
//if array had 7 items, then print row of 4 next row 3
//if array had 16 items, print 4 rows of 4, etc.
$height = sizeof($aaPlaceholder);//get size of array
//loop through array of X items, for each group of 4 print as a row
for($row = 0; $row < $height; $row++) //looping through the rows
{
echo '<div class="row flush">'; //open div
for($image = 0; $image < 4; $image++) //each row is composed of 4 images
{
foreach($aaPlaceholder as $key => $value) {
printf(TEMPLATE_PORTFOLIO, $key, $value);
//replaced $template with constant TEMPLATE_PORTFOLIO!
}
}
echo '</div>'; //end div group of 4
}//end loop
}//end function
If the answer is obvious, please remember i'm very new and it's not obvious to me or honestly I would not be asking.
Thank you for any help or guidance
cheers
First, the height is not the size of the array but it is a fourth of it.
Second, the inner foreach, as already stated in the comments, should not be changed: it should be deleted. You are already looping through your elements, no need to do it once more.
function PrintFolio($aaPlaceholder)
{
//print out two rows of four from array with 8 items
//if array had 7 items, then print row of 4 next row 3
//if array had 16 items, print 4 rows of 4, etc.
$itemsCount = sizeof($aaPlaceholder);//get size of array
$height = (int)ceil(sizeof($aaPlaceholder)/4);//get size of array divided by 4
//loop through array of X items, for each group of 4 print as a row
for($row = 0; $row < $height; $row++) //looping through the rows
{
echo '<div class="row flush">'; //open div
for($image = 0; $image < 4; $image++) //each row is composed of 4 images
{
$aaPlaceholderIndex = $row*4+$image; //the index in the original array
if( $aaPlaceholderIndex < $itemsCount ) {
printf(TEMPLATE_PORTFOLIO, $aaPlaceholderIndex, $aaPlaceholder[$aaPlaceholderIndex]);
}
}
echo '</div>'; //end div group of 4
}//end loop
}//end function
EDIT: this works if your array has plain numeric keys from 0 to n. Otherwise (e.g. associative array) it should read $aaPlaceholderIndex = array_keys($aaPlaceholder)[$row*4+$image];
EDIT AGAIN: so you use associative arrays (key are strings and not integers 0..n). I rushed a bit my edit about this. You'd better:
define $keys = array_keys($aaPlaceholder); outside the loops, where you define $height
define $aaPlaceholderIndex = $keys[$row*4+$image];
move this definition inside the "if" statement, which becomes
if( $row*4+$image < $itemsCount ) {
$aaPlaceholderIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPlaceholderIndex, $aaPlaceholder[$aaPlaceholderIndex]);
}
This way you run array_keys just once (good for performance) and you avoid a Notice "Undefined offset" when retrieving $keys[$row*4+$image] when $row*4+$image is too big.
This is probably not the best answer, but this is what I figured out to do.
I created a new variable called 'limit' which is equal to the height var divided by four. I then commented out the second 'for loop' as it was causing problems, leaving only the first for loop and the foreach loop. This gave me back my array as hoped.
Revised code below:
function PrintFolio($aaPlaceholder)
{
//print out two rows of four from array with 8 items
//if array had 7 items, then print row of 4 next row 3
//if array had 16 items, print 4 rows of 4, etc.
$height = sizeof($aaPlaceholder);//get size of array
$limit = $height % 4;
//loop through array of X items, for each group of 4 print as a row
for($row = 0; $row <= $limit; $row++) //looping through the rows
{
echo '<div class="row flush">'; //open div
//for($image = 0; $image < 4; $image++) //each row is composed of 4 images
//{
foreach($aaPlaceholder as $key => $value) {
printf(TEMPLATE_PORTFOLIO, $key, $value);
//replaced $template with constant TEMPLATE_PORTFOLIO!
}
//}
echo '</div>'; //end div group of 4
}//end loop
}//end function
I have come to this part of script so far:
dif($result>0)
{
$ii=0;
$jj=0;
while (odbc_fetch_row($result))
{
for ($jj = 1; $jj <= odbc_num_fields($result); $jj++)
{
$rr[$ii][$jj]=odbc_result($result,$jj);
if(is_null($rr[$ii][$jj]))
$rr[$ii][$jj] = noData;
echo $rr[$ii][$jj];
echo "<br />";
}
$ii++;
}
}
This works good for creating and populating dynamic tables. But i need also to create dynamic number of single line arrays which consist of column values of arrays i get previously.
Example:
if i get
Array1
2012.01.01 10 20 30
2012.01.02 1 2 3
2012.01.03 11 22 33
i need to convert to
Array2
2012.01.01 2012.01.02 2012.01.03
Array3
10 1 11
Array4
20 2 22
Array5
30 3 33
As i mentioned before the first part of script is needed, so is there a possibility to use result to create single line arrays for further use? I suppose i'm missing something...
What is wrong with a for loop and adding the elements to an array?'
$rr = array(array(1,2,3,4,5),array(6,7,8,9,0),array(11,22,33,44,55));
$result = array();
for($j=0;$j<count($rr[0]);$j++){
$col = array();
for($i=0;$i<count($rr);$i++) {
array_push($col,$rr[$i][$j]);
}
array_push($result,$col);
}
print_r($result);
for a demo see this codepad: http://codepad.org/wgSCtoMV
This is what my code does:
it gets 4 rows from my table, stores them in an array, repeats them untill they reach 20 inside that array then echo's them whit a foreach loop... problem is i get an empty result at the end of each foreach cycle of the 4 results.
$result = mysql_query("SELECT * FROM ".$table."");
$row_nr = mysql_num_rows($result); // Find out how many rows I have in the table, lets say 4
while($rows = mysql_fetch_assoc($result)){
$arrayrows[] = $rows; // Put my 4 rows in the array
}
// Now I multiply nr. of rows to reach desired number which is 20
$dbRow=0;
for($n=0; $n <= 20; $n++)
{
if($dbRow > $row_nr) $dbRow = 0;
$fullarrayrows[$n] = $arrayrows[$dbRow];
$dbRow++;
}
// after some php pagination code I slice the array:
$arrayslice = array_slice($fullarrayrows, $offset, $rowsperpage);
// Now i display my array
foreach($arrayslice as $slice)
{
echo ''.$slice['name'].'';
echo '<br />';
}
Problem is I get some empty records in the foreach
name1name2name3name4HERE I GET THE EMPTY ENTRYname1name2name3name4AGAIN I GET THE EMPTY ENTRY
... and so on, at the end of each cycle
Thank you very much , please give me an ideea of what's wrong:)
$dbRow indexes start at 0 and end at 3
but $row_nr equals 4
so change this line
if($dbRow > $row_nr) $dbRow = 0;
to
if($dbRow >= $row_nr) $dbRow = 0;
I currently have:
$i = 1;
while {
echo $i;
$i++;
}
And it shows:
1
2
3
4 etc..
How would I make it display backwards?
For example
4
3
2
1 etc..
I basically want to do the exact same thing but flip it around.
$i = 10;
while($i>0) {
echo $i;
$i--;
}
Example - Print number through 0 to 5 with PHP For Loop
for($i=0; $i<=5; $i=$i+1)
{
echo $i." ";
}
In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1.
The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.
Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.
Example - Print number through 5 to 0 with PHP For Loop
What if we want to go backwards, that is, print number though 0 to 5 in reverse order? We simple initialize the counter variable $i to 5, set its condition to 0 and decrement $i by 1.
for($i=5; $i>=0; $i=$i-1)
{
echo $i." ";
}
The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.
Good luck! :)
If you want to back-word sr number as per your count of rows in result then use this.
$num_rows = mysqli_num_rows($query);
$x = $num_rows;
$x--;
$i = 4;
while($i > 0) {
echo $i--;
}