Php/Jquery add rows while looping through data - php

I have a database with "7" user account objects.
I have called the objects using any of the loop functions.
foreach (objects as object) {
echo '<div class="col-4>"'.object->property.'"</div>';
}
I want to add rows for each 3 columns as they are being displayed.
The above code would result in all my objects/colums/divs being nested in one row.
I want a way in which I can have the loop adding a row for every 3 columns.

Count the objects as you go. If $x divided by 3 has no remainder, close and open the next div:
$x = 0;
foreach ($objects as $object){
$x ++;
echo '<div class="col-4">"'.$object->property.'"</div>';
echo ($x % 3 == 0) ? '</div><div class="row">' : '';
}

Related

Php count elements inside loop not outside

I know how to count elements inside a loop, but tried and can´t find a solution. Actually, I can count the elements in loop in this way:
$i = 0;
foreach ($Contents as $item)
{
$i++;
}
echo $i;
But in my case, I have large function and I can do this, but need more time for count elements inside. I can´t put the string for showing number elements inside loop outside of the function. I must show inside loop all number of elements and show as this. Here's an example:
$i = 0;
foreach ($Contents as $item)
{
print "Number Elements it´s : $i";
print "Element ".$i."<br>";
$i++;
}
The problem here is that the phrase "number elements it´s" always repeats, because inside loop, and all time $i show me 0,1,2,3,4,5 ...... and all time the same as number of elements inside loop.
My idea and question is if it´s possible inside loop to show the number of elements and after this show the elements as this structure when executing the script:
Númber elements it´s : 12
Element 1
Element 2
Element 3
.
.
.
.......
This it´s my question. I hope you understand it all. Thanks in advance.
As mentioned in the comments, youu will need to use the count() function for that. If you insist on having it inside the loop, simply do it like this:
$i = 0;
foreach ($Contents as $item)
{
if($i == 0) {
print "Number of Elements is : " . count($Contents) . "<br><br>";
}
print "Element ".$i."<br>";
$i++;
}

Function returns undefined offset error

I'm trying to resolve the undefined offset. I've Google and looked through stack overflow, but the examples I've found either didn't apply or were too complex for someone of my skill to fathom at this time. I'm very green, but I'd done diligence I promise before asking for help and wisdom.
This is the function as it now exists:
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//print out X number rows of unto 4 images from array with X items
//if array had 7 items, print one row of 4 next row 3
//if array had 16 items, print 4 rows of 4, etc.
//if array had 13 items, print 3 rows of 4, final row with one item
$itemsCount = sizeof($aaPh);//get size of array
$height = (int)ceil(sizeof($aaPh)/4);//rounded up division by 4
//$height = $height + 1;
$keys = array_keys($aaPh); //get keys
//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
{
$aaPhIndex = array_keys($aaPh)[$row*4+$image]; //if associative array
if( $row*4+$image < $itemsCount ) {
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
//$template = '<div class="3u"><img src="_img/thumbs/%1$s" alt="" title="%2$s" /></div>';
}
}
echo '</div>'; //end div group of 4
}//end loop
}//end function
It takes an array, slices it up in to units of four and then prints the array as a series of images to the screen. But if I don't have a number which is exactly devisable by 4, it will display whatever open slots remain as undefined offset errors (I hope I am saying that correctly).
My goal is to not have the undefined offset errors print to these screen without revising my site error reporting capabilities (I think doing that would be cheating as it wouldn't correct the problem, just hide it which doesn't seem very above board to me).
Why don't you just put a line break after each 4th element?
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//loop through the array
for($row = 0; $row < Count($aaPh); $row++) //looping through the rows
{
if (!$row || !($row%4)) {
if ($row) echo '</div>'; // close previously opened divs
echo '<div class="row flush">'; //open div
}
/* show your picture code here */
}//end loop
echo '</div>';
}//end function
Here is an update after your comments.
Because you do not need values of your associative array, only keys, the code can be changed as follows:
function PrintFolio($aaPh) //aaPh =associative array place holder
{
//loop through the array
$row=0;
foreach(array_keys($aaPh) as $img) //looping through array keys only
{
if (!$row || !($row%4)) {
if ($row) echo '</div>'; // close previously opened divs
echo '<div class="row flush">'; //open div
}
echo '<img src="' . $img . '">';
$row++; // increase row counter.
}//end loop
echo '</div>';
}//end function
Make sure to put proper path into the tag
Since you can't assume that you're always going to have a number of elements that's exactly divisible by four, you need to test each one. In your inner loop where you calculate the index and then use it to refer to the array, just add a check to ensure that array element exists. From this:
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
To this:
$aaPhIndex = $keys[$row*4+$image];
if (isset($aaPh[$aaPhIndex])) {
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
}
The error in your logic is that on this line
for($image = 0; $image < 4; $image++) //each row is composed of 4 images
You assume there are always 4 images. But like you said yourself, if the array has for example 13 items, then the last row will only contain one image. This will cause $aaPhIndex = array_keys($aaPh)[$row*4+$image]; to access an array index that doesn't exist.
To solve the problem you will either have to modify $image < 4 to also account for the last row, or just check that the index doesn't exceed the item count. For example by placing the error line under the condition that you already wrote:
if( $row*4+$image < $itemsCount ) {
$aaPhIndex = array_keys($aaPh)[$row*4+$image]; //if associative array
$aaPhIndex = $keys[$row*4+$image];
printf(TEMPLATE_PORTFOLIO, $aaPhIndex, $aaPh[$aaPhIndex]);
//$template = '<div class="3u"><img src="_img/thumbs/%1$s" alt="" title="%2$s" /></div>';
}
Hope this works

How to create new DIV every 8 MySQL rows queried

im trying to figure out how to create new DIV every 8 MySQL rows queried. I am integrating jPagination into my site and so I need to create a new DIV container every 8 rows it receives from the database. Any ideas?
you need this: %
not sure about how your code exactly goes, but in the loop of every row you make a count++ and then something like this which would be in C:
if(!count%8) {
print DIV eccc
}
just so you understand what this % does: it gives you the remainer of a division. For example, if your row is number 20, so count equals to 20 at that moment, 20%8 will equal 4. That is because if you divide 20/8 you will have 2.** something, then multiply 2*8 you get 16. Take 20-16 = 4. So 20%8 is 4. Only when the number in count++ is perfectly divisible by number 8 you will get 0 zero there. So your IF statement says: if there ia no remain dividing count by 8 then do this
maxim
i = 1
while( gettingRows )
{
doWhateverYouDoHere()
if ( i%8 === 0 )
print "div"
++i
// or put increment right into the if statement like ( if i++ % 8 === 0 )
}
<?php
// previous code.....
$counter = 1;
echo '<div class="outercssclass">';
echo '<div class="innercssclass">';
// fetch mysql query data into $results....
// you can do validations with mysql_num_rows to check the number of rows the query returned
foreach($results as $result) {
$counter++;
if($counter % 8 == 0) {
echo '</div><div class="innercssclass">';
}
// other logic...
// rest of the code
}
echo '</div>'; // for closing the inner div
echo '</div>'; // for closing the outer wrapper div
// rest of the program logic...

Count results inside foreach then store that value in a variable to be used elsewhere

How do you count the results inside a foreach then store that value in a variable to be used on another foreach.
Example. This foreach returns 5 items
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:
foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
echo "$item->name";
echo "$item->address";
if_blah_blah_meet_condition_then_break;
}
So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.
How can I achieve this? Please advice.
Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.
Code:
$i = 0;
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
}
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
if ($i > 5) { // or whatever the number is
break;
}
}
$totalItems = count($xml->items);
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Just use count($xml->items) and that value in the condition, inside the loop.
It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_one[] = $item;
}
}
//whatever changes you do to $xml->items
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_two[] = $item;
}
}
Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.

too many rows created in drupal view

I have modified the tpl used for the grid view to show 3 columns of content, my only issue that the code below creates unneeded divs for the view. I have a maximum of 9 items that should be output in 3 rows, 3 per column. What's the best way to modify the code below? to prevent the extra divs from being output.
<?php foreach ($rows as $row_number => $columns): ?>
<div>
<?php foreach ($columns as $column_number => $item): ?>
<?php print $item; ?>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
I would drop that notation of foreach syntax (but I think that's pretty personal :-) )
You could use the modulo to check if you just had 3 columns (if I understood your question).
<?php
// I´m assuming that $column_number is a zero based index
// if thats not the case you should add a counter to keep track of column numbers or if it is in sequence but isn't zero based you could easily update the calculates based in your starting index
foreach ($rows as $row_number => $columns) {
foreach ($columns as $column_number => $item) {
if ($column_number == 0 || $column_number%3 == 0) {
print '<div>';
}
print $item;
if ($column_number == 2 || $column_number%3 == 2) {
print '</div>';
}
}
// prevent open div tags
$total_columns = count($columns);
if ($total_columns > 0 && ($total_columns < 3 || $total_columns%3 != 0)) {
print('<div>');
}
}
I've also dropped all those opening and closing tags of php for readability.

Categories