stuck with simple php looping logic - php

I have an array which can have any no. of elements in it. Now i want to loop this array and create design such that each li can have 15 elements inside it , next set of li will be created based of multiples of 15's elements.
Now my array has exact 15 elements and the code i am trying creating 2 li , which it should create only 1 li.
May be my logic is too bad or I am missing anything.
Here is my code:-
<?php $result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); ?>
<div class="slide">
<?php $design = '<ul class="slides"><li><div class="MainSlider">';
foreach($result as $key=>$row)
{
$design .= '<div class="MainSliderPic">'.$key.'</div>';
if(($key+1)% 15 == 0){
$design .= '</div></li><li><div class="MainSlider">';
}
if(count($result) == $key+1){
$design .= '</div></li></ul>';
}
}
echo $design;
?>
</div>

You can use array_chunk for to achieve it:
$result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$chunks = array_chunk($result, 15);
foreach ($chunks as $chunk) {
echo '<ul><li>';
echo implode('</li><li>', $chunk);
echo '</li></ul>';
}

Don't mix opening and closing of tags in your code. Do it separately where it belongs, e.g.
$design = '<ul class="slides">';
$n = 0;
foreach($result as $key=>$row) {
if ($n == 0)
$design .= '<li><div class="MainSlider">';
$design .= '<div class="MainSliderPic">' . $key . '</div>';
++$n;
if ($n == 15) {
$design .= '</div></li>';
$n = 0;
}
}
$design .= '</ul>';
echo $design;

Try following code:
<?php $result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); ?>
<div class="slide">
<?php $design = '<ul class="slides"><li><div class="MainSlider">';
foreach($result as $key=>$row)
{
$design .= '<div class="MainSliderPic">'.$key.'</div>';
if((($key+1)% 15 == 0) && (count($result) != ($key+1))){
$design .= '</div></li><li><div class="MainSlider">';
}
if(count($result) == $key+1){
$design .= '</div></li></ul>';
}
}
echo $design;
?>
</div>

Related

PHP - How to wrap every 2 items of a 'for' loop within a div

I'm looking for a way to wrap every too items of this very basic for loop within a div :
<?php
for( $i=1; $i<=50; $i++ )
{
echo "<div><a href='item-".$i."'>".$i."</a></div>";
}
?>
This produces the following :
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
The output i need would be :
<div>1 2</div>
<div>3 4</div>
Thanks
Easiest way i can think of is by doing this. This also works if you have a resultset from a database, or an array of item objects, just replace the range() function with the array.
<?php
foreach (array_chunk(range(1, 50), 2) as $chunk) {
echo "<div>";
foreach ($chunk as $itemId) {
echo "<a href='item-" . $itemId . "'>" . $itemId . "</a>";
}
echo "</div>" . PHP_EOL;
}
Use modulo operator
code:
<?php
$chunks = 2;
$display = true;
for( $i=1; $i<=6; $i++ )
{
if ($display && ($i % $chunks || $chunks === 1)) {
echo "<div>";
$display = false;
$last = true;
}
echo "<a href='item-".$i."'>".$i."</a>";
if (!($i % $chunks)) {
echo "</div>" . PHP_EOL;
$display = true;
$last = false;
}
}
if ($last) {
echo "</div>" . PHP_EOL;
}
generates:
<div><a href='item-1'>1</a><a href='item-2'>2</a></div>
<div><a href='item-3'>3</a><a href='item-4'>4</a></div>
<div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and with:
$chunks = 3;
you will get:
<div><a href='item-1'>1</a><div><a href='item-2'>2</a><a href='item-3'>3</a></div>
<div><a href='item-4'>4</a><div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and so one.

HTML every nth iteration with a twist--the nth changes every xth time using array values

Everyone knows how to output a bit of html every nth iteration in a foreach loop.
$i=0;
foreach($info as $key){
if($i%3 == 0) {
echo $i > 0 ? "</div>" : ""; // close div if it's not the first
echo "<div>";
}
//do stuff
$i++;
}
I'm trying to do this same thing, but instead of a known value for $i, I'm pulling values in from an array like
Array(0=>2, 1=>1, 2=>5)
so that instead of
<div>
item
item
item
</div>
<div>
item
item
item
</div>
<div>
item
item
item
</div>
I can get something like this:
<div>
item
item
</div>
<div>
item
</div>
<div>
item
item
item
item
item
</div>
But I just can't get it to work. I think I'm close, but something's just escaping me. Any ideas?
Here's the code I'm running right now:
//$footnote = array of values
$i=0;
$m=0;
$bridge .= '<div class="grid block menu">';
foreach($value['sections'] as $section) {
if ($i++%$footnote[$m] === 0) {
$bridge .= '</div><div class="grid block menu">';
$m++;
}
$secname = $section['name'];
$dishcount = count($section['items']);
$bridge .= '<h3>'. $secname .' '.$footnote[0].'</h3>';
$i++;
} //end section foreach
$bridge .= '</div>';
I think the issue you're having is in the if($i++%...) section of your code.
Instead of incrementing $i and checking the result of the modular expression, just check if $i == $footnote[$m] and then reset $i back to 0 when it is a success.
I modified your script a little locally, try this out:
$i = $m = 0;
$bridge .= '<div class="grid block menu">';
foreach($value['sections'] as $section)
{
if ($i == $footnote[$m])
{
$bridge .= '</div><div class="grid block menu">';
$m++;
$i = 0;
}
$secname = $section['name'];
$dishcount = count($section['items']);
$bridge .= '<h3>'. $secname .' '.$footnote[$m].'</h3>';
$i++;
}
$bridge .= '</div>';
This way, you are actually iterating through each footnote instead of just checking to see if it is divisible by the number specified.
Untested code, let me know if any changes are necessary so I can update the answer appropriately.
// Calculate section breaks
$sections = [ 2, 1, 5];
$sectionBreaks = [];
$sum = 0;
foreach ($sections as $section) {
$sum += $section;
$sectionBreaks[] = $sum;
}
// Add the items to each section
$results = [];
$result = '';
$i = 0;
foreach ($items as $item) {
if (array_search($i, $sectionBreaks) !== false) {
$results[] = $result;
$result = '';
}
$result .= '<h3>' . $item . '</h3>';
}
// Collapse it all together
$finalResult = '<div>' . implode('</div><div>', $results) . '</div>';
This is the way to loop thru data in order to achieve the example you exposed at first. foreach and for. This works, but unless you give us some data to work with I wont be able to adjust it to it.
$bridge='';
foreach($value['sections'] as $section) {
$bridge .= '<div class="grid block menu" number="'.$section.'"><h3>MY TITLE!! '. $section['name'] .'</h3>';
for ($x = 0; $x <= $section; $x++) {
$bridge .= "Here goes the content; Item $x<br>";
}
$bridge .= '</div>';
}
echo $bridge;
I hope it helps :)

Group MySQL results into blocks of A-Z in PHP

I have a list of thousands of results and I want to group them alphanumerically for example, I need it to be like this:
<h1>0-9</h1>
<ul>
<li>011example</li>
<li>233example</li>
<li>65example</li>
</ul>
<h1>A</h1>
<ul>
<li>albert</li>
<li>alfred</li>
<li>annie</li>
</ul>
<h1>B</h1>
<ul>
<li>ben</li>
<li>bertie</li>
<li>burt</li>
</ul>
But I can't work out how to split or group my results into 0-9 and A-Z.
Currently I have:
<?php
$get_az = mysql_query("SELECT custom_22 FROM db_table1");
echo '<ul>';
while ($row = mysql_fetch_assoc($get_az)) {
$getfirstletter = substr($row['custom_22'], 0,1);
$name = $row['custom_22'];
echo '<h1>'.$getfirstletter.'</h1>';
echo '<li>'.$name.'</li>';
}
echo '</ul>';
?>
Order by the name and handle each letter one by one.
$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) {
$first_letter = strtolower(substr($row['custom_22'], 0, 1));
if (preg_match("/[0-9]/", $first_letter)) { // detect digits
$first_letter = "0-9";
}
if ($first_letter !== $current_first_letter) {
if ($current_first_letter !== null) {
echo '</ul>';
}
echo '<h1>' . $first_letter . '</h1>';
echo '<ul>';
}
$current_first_letter = $first_letter;
echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
echo '</ul>';
}
I would do it this readable way:
$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');
$groups = array();
split results to groups
while ($row = mysql_fetch_assoc($get_az)) {
$firstLetter = strtolower(substr($row['custom_22'], 0, 1));
check for digits
if (is_numeric($firstLetter)) {
$firstLetter = '0-9';
}
if (isset($groups[$firstLetter]) === false) {
$groups[$firstLetter] = array();
}
$groups[$firstLetter][] = $row['custom_22'];
}
simply iterate over groups and echoes it
foreach ($groups as $h1 => $items) {
echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
echo '<ul>';
foreach ($items as $item) {
echo sprintf('<li>%s</li>', htmlspecialchars($item));
}
echo '</ul>';
}

Php Array list items with different class

This is my current array that displays list items in a unordered list.
function get_bottle_colors() {
if(empty($_GET['cap_id'])) return false;
$constructor_img = get_post_meta($_GET['cap_id'], 'product_constructor_image', true);
if(is_array($constructor_img) && count($constructor_img)>0 && !empty($constructor_img[0]['title'])){
$output = '<label>Bottle Color</label><ul>';
foreach ($constructor_img as $key => $image) {
if(empty($image['image'])) continue;
$output .= '<li><a href="'.$image['image'].'" data-width="'.$img_size[0].'" data-height="'.$img_size[1].'"';
$output .= '</a></li>';
}
$output .= '</ul>';
}else{
$output = '<label>Bottle Color</label><ul></ul>';
}
echo $output;
die();
}
In total there will be up to 16 list items generated by this. I need each list item to have its own class eg: list class="red", list class="green", etc. Any idea how i go about achieving this?
Found the solution thanks to Anant. Had to declare the class array like below.
function get_bottle_colors() {
if(empty($_GET['cap_id'])) return false;
$constructor_img = get_post_meta($_GET['cap_id'], 'product_constructor_image', true);
if(is_array($constructor_img) && count($constructor_img)>0 && !empty($constructor_img[0]['title'])){
$output = '<label>Bottle Color</label><ul>';
$i = 0;
$class_array = array("a","b","c","d","e","f","g","h","i","j","k","l","n","m","n","o","p");
foreach ($constructor_img as $key => $image) {
if(empty($image['image'])) continue;
$category = 9;
$img_size = getimagesize($image['image']);
$output .= '<li class= "'.$class_array[$i].'"><a href="'.$image['image'].'" data-width="'.$img_size[0].'"
data-height="'.$img_size[1].'"';
$output .= 'data-id="'.$_GET['cap_id'].'_'.$key.'" data-part="#constructor-bottles" class="sub-caps">'.$image['title'];
$output .= '</a></li>';
$i++;
}
$output .= '</ul>';
}else{
$output = '
<label>Bottle Color</label><ul></ul>'; } echo $output; die(); }

Loop through mysqli results array once to get all information

I am querying the database for data, but in order to do what I need, I end up looping through that results array at least three times. How do I get all of the info I need out of the array without having to loop so many times? I need to get data from the array based on the results from the previous loops. The code below is the only way I could figure out in order to only query the database once.
$recordSQL = mysqli_query($link, $sqlString);
$resultMonths = array();
while($recordResult = mysqli_fetch_assoc($recordSQL)) $resultMonths[] = $recordResult['date'];
mysqli_data_seek($recordSQL, 0);
$uniqueMonths = array_unique($resultMonths);
foreach($uniqueMonths as $key => $date){
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
$resultCompanies = array();
while($companyResult = mysqli_fetch_assoc($recordSQL)){
if($companyResult['date'] == $date) $resultCompanies[] = $companyResult['company'];
}
mysqli_data_seek($recordSQL, 0);
$uniqueCompanies = array_unique($resultCompanies);
$oldco = '';
foreach($uniqueCompanies as $key => $company){
$x = 0;
while($typeResult = mysqli_fetch_assoc($recordSQL)){
if($typeResult['date'] == $date && $typeResult['company'] == $company){
if($oldco != $typeResult['company']){
if($x != 0) echo '</div>';
echo '<div class="company-record">'.$typeResult['name'].' - ';
}
if($x > 0) echo ', ';
echo translateID('Type', $typeResult['type']).'('.translateID('Section', $typeResult['section']).')';
$oldco = $typeResult['company'];
$x++;
}
}
echo '</div>';
mysqli_data_seek($recordSQL, 0);
}
}
FYI, you are actually looping N**3 times. Do it this way:
$month_company_rows = array();
while ($row = mysqli_fetch_assoc($recordSQL)) {
$month_company_rows[$row['date']][$row['company']][] = $row;
}
foreach ($month_company_rows as $date => $company_rows) {
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
foreach ($company_rows as $company => $rows) {
echo '<div class="company-record">'.$company.' - ';
foreach ($rows as $x => $row) {
if($x > 0) echo ', ';
echo translateID('Type', $row['type']).'('.translateID('Section', $row['section']).')';
}
echo '</div>';
}
}

Categories