html in foreach loop - php

I have a problem with embeded html in foreach loop:
HTML:
<div class="head">
<div class="wins">
<div class="images">
<img src="images/1.jpg" alt="">
<img src="images/2.jpg" alt="">
<img src="images/3.jpg" alt="">
</div>
<div class="Bar">
<span>1</span>Cat1
<span>2</span>Cat2
<span>3</span>Cat3
</div>
</div>
I want to print html with this function :
function Bar($array){
$box .= '<div class="images">';
foreach($array as $key => $value){
$box .= ' <img src="'.$value['image'].'" alt="">';
}
$box .= '</div>';
return $box;
}
I want to break the loop after <div class="images"> and continue loop after the <div class="Bar"> . But Im confusing about this issue. Please show me the right way.
Thanks in advance

Two options:
Run through the loop twice.
or
Store each section in a separate variable and merge them later on, i.e.
function Bar($array){
foreach($array as $key => $value){
$images .= ' <img src="'.$value['image'].'" alt="">';
$bar .= ' <span>....';
}
$box .= '<div class="images">';
$box .= $images;
$box .= '</div>';
$box .= '<div class="Bar">';
$box .= $bar;
$box .= '</div>';
return $box;
}

function Bar($array){
$divImage=$divBar=array();
foreach($array as $key => $value){
$divImage[]= " <a href='#' ><img src='{$value['image']}' alt=''></a>";
$divBar[]= " <a href='#' rel='$key' ><span>$key</span>Cat$key</a>";
}
$divImage="<div class='images'>".implode("\r\n",$divImage)."</div>";
$divBar="<div class='bar'>".implode("\r\n",$divBar)."</div>";
$box="<div class='wins'>
$divImage
$divbar
</div>";
return $box;
}

maybe something like that?
$divimg = '<div class="images">';
$divbar = '<div class="Bar">';
foreach(...) {
$divimg .= ' ... ';
$divbar .= ' ... ';
}
$divimg .= '</div>';
$divbar .= '</div>';
$divimg .= $divbar;
return $divimg;

Related

How to insert HTML using foreach() without echo

I have this working code in my view:
<?php
$task_num = 0;
foreach ($curent_day->getTasksList() as $task){
echo '<div class="task">';
echo '<span class="task_id">'.($task_num+1).'.'.'</span>';
echo '<div class="task_time">';
echo '<span class="task_time_start">'.$task->getStartTime().'</span>';
echo '<span class="task_time_finish">'.$task->getFinishTime().'</span>';
echo '</div>';
echo ''.$task->name.'';
echo 'Start';
echo 'Finish';
echo '<div class="status_round '.$task->status.'"></div>';
echo '</div>';
$task_num++;
}
?>
Is there any way to get rid of 'echo'?
P.S. and is the way to insert HTML with HTML helper more correct even if it takes more space?
You can drop echo completely and use native HTML syntax:
<?php $task_num = 0 ?>
<?php foreach ($curent_day->getTasksList() as $task): ?>
<div class='task'>
<span class='task_id'><?= ++$task_num ?></span>
<div class='task_time'>
<span class='task_time_start'><?= $task->getStartTime() ?></span>
<span class='task_time_finish'><?= $task->getFinishTime() ?></span>
</div>
<a href='/' class='task_name'><?= $task->name ?></a>
<a href='/' class='btn task_start btn_disabled'>Start</a>
<a href='/' class='btn task_finish btn_disabled'>Finish</a>
<div class='status_round <?= $task->status ?>'></div>
</div>
<?php endforeach ?>
This will give you better syntax highlighting and autoformatting support in your IDE/editor.
There are several different ways that you can concatenate the string by using single quotes and double quotes, or by using a variable and the ".=" operator to append text onto the end of a string. Just google php strings & concatenation and it will have more than you need to figure this out.
But using you example here is a method:
$task_num = 0;
foreach ($curent_day->getTasksList() as $task){
echo
'<div class="task">' .
'<span class="task_id">' . ($task_num+1) . '.'.'</span>' .
'<div class="task_time">' .
'<span class="task_time_start">' . $task->getStartTime() . '</span>' .
'<span class="task_time_finish">' . $task->getFinishTime() . '</span>' .
'</div>' .
''.$task->name.'' .
'Start' .
'Finish' .
'<div class="status_round '.$task->status.'"></div>' .
'</div>';
$task_num++;
}
You have to echo to output you data to the browser.
You need not use string concatenation or multiple echo statements.
Alternative
$task_num = 0;
foreach ($curent_day->getTasksList() as $task){
$task_num++;
echo
"<div class='task'>
<span class='task_id'>{$task_num}</span>
<div class='task_time'>
<span class='task_time_start'>{$task->getStartTime()}</span>
<span class='task_time_finish'>{$task->getFinishTime()}</span>
</div>
<a href='/' class='task_name'>{$task->name}</a>
<a href='/' class='btn task_start btn_disabled'>Start</a>
<a href='/' class='btn task_finish btn_disabled'>Finish</a>
<div class='status_round {$task->status}'></div>
</div>";
}
You can concatenate your html in one variable and then you can use it with one time echo statement
<?php
$task_num = 0;
$html = '';
foreach ($curent_day->getTasksList() as $task){
$html .= '<div class="task">';
$html .= '<span class="task_id">'.($task_num+1).'.'.'</span>';
$html .= '<div class="task_time">';
$html .= '<span class="task_time_start">'.$task->getStartTime().'</span>';
$html .= '<span class="task_time_finish">'.$task->getFinishTime().'</span>';
$html .= '</div>';
$html .= ''.$task->name.'';
$html .= 'Start';
$html .= 'Finish';
$html .= '<div class="status_round '.$task->status.'"></div>';
$html .= '</div>';
$task_num++;
}?>

using php to place image names within a folder to feed HTML img src inside bootstrap carousel

I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.
After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).
My code is below. I have two question about it:
(obviously) Why is it not working?
Is there a better way to separate such a long PHP function from the HTML code (like a call with include but that would work with functions)?
<div class="container-fluid">
<?php
$img_folder = './img/img_animazione/';
function carousel_loop($folder)
{
echo '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
echo '<ol class="carousel-indicators">';
$i = -1;
$images = scandir($folder);
foreach($images as $image) {
$i++; //$i is the index of the current loop.
if ($i == 0) {
echo '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
} else {
echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
}
}
echo '</ol>';
echo '<div class="carousel-inner">';
foreach($images as $image) {
if ($image === reset($images)) {
echo '<div class="item active">';
echo '<img src="' . $image . '" alt="'. $image . '">';
echo '</div>';
} else {
echo '<div class="item">';
echo '<img src="' . $image . '" alt="'. $image . '">';
echo '</div>';
}
}
echo '</div>';
echo '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
echo '<span class="glyphicon glyphicon-chevron-left"></span>';
echo '<span class="sr-only">Previous</span>';
echo '</a>';
echo '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
echo '<span class="glyphicon glyphicon-chevron-right"></span>';
echo '<span class="sr-only">Next</span>';
echo '</a>';
echo '</div>';
}
carousel_loop($img_folder);
?>
</div>
That's not the way to use functions. You can't echo like that from inside the function. You have to build up the HTML inside the function and return it. Then either just echo the function or assign what it returns to a variable.
So like this:
<?php
function carousel_loop($folder)
{
html = "";
html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
html .= '<ol class="carousel-indicators">';
$i = -1;
$images = scandir($folder);
foreach($images as $image) {
$i++; //$i is the index of the current loop.
if ($i == 0) {
html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
} else {
html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>';
}
}
html .= '</ol>';
html .= '<div class="carousel-inner">';
foreach($images as $image) {
if ($image === reset($images)) {
html .= '<div class="item active">';
html .= '<img src="' . $image . '" alt="'. $image . '">';
html .= '</div>';
} else {
html .= '<div class="item">';
html .= '<img src="' . $image . '" alt="'. $image . '">';
html .= '</div>';
}
}
html .= '</div>';
html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
html .= '<span class="sr-only">Previous</span>';
html .= '</a>';
html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
html .= '<span class="sr-only">Next</span>';
html .= '</a>';
html .= '</div>';
return html;
}
?>
<div class="container-fluid">
<?php
$img_folder = './img/img_animazione/';
echo carousel_loop($img_folder);
?>
</div>
Thanks to #Abraham A. answer, I finally was able to come up with a working (still "dirt") solution. I'll post the code below. The problems in my initial code were:
Using echo within a function instead of returning a (very long) HTML string in the function and "echoing" it from outside.
<img src= obviously wants a source and not just a filename. My first attempt was <img src= . $image, the correct form is <img src= . $folder . DIRECTORY_SEPARATOR . $image
It seems like [scandir()][1] creates an array with all the filenames within a folder AND ".", ".." (current and parent folder) in it. I got rid of the latters via $allFiles = scandir($folder); $images = array_diff($allFiles, array('.', '..')); as suggested here.
My working code is this one now.
<?php
function carousel_loop($folder)
{
$html = "";
$html .= '<div id="myCarousel" class="carousel slide" data-ride="carousel">';
$html .= '<ol class="carousel-indicators">';
$i = -1;
$allFiles = scandir($folder); // list all files in folders
$images = array_diff($allFiles, array('.', '..')); // drop current and parent folder from array list (".", "..")
foreach($images as $image) {
$i++; //$i is the index of the current loop.
if ($i == 0) {
$html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>';
} else {
$html .= '<li data-target="#myCarousel" data-slide-to="' . $i . '"></li>';
}
}
$html .= '</ol>';
$html .= '<div class="carousel-inner">';
foreach($images as $image) {
if ($image === reset($images)) {
$html .= '<div class="item active">';
$html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
$html .= '</div>';
} else {
$html .= '<div class="item">';
$html .= '<img src="' . $folder . DIRECTORY_SEPARATOR . $image . '" alt="' . $image . '" style="width:100%;">';
$html .= '</div>';
}
}
$html .= '</div>';
$html .= '<a class="left carousel-control" href="#myCarousel" data-slide="prev">';
$html .= '<span class="glyphicon glyphicon-chevron-left"></span>';
$html .= '<span class="sr-only">Previous</span>';
$html .= '</a>';
$html .= '<a class="right carousel-control" href="#myCarousel" data-slide="next">';
$html .= '<span class="glyphicon glyphicon-chevron-right"></span>';
$html .= '<span class="sr-only">Next</span>';
$html .= '</a>';
$html .= '</div>';
return $html;
}
?>
<div class="container">
<?php
$img_folder = './img/img_animazione';
echo carousel_loop($img_folder);
?>
</div>

How do I get multiple images from a single string

I've looked around and haven't found a answer that did it for me. I don't want all the images from an HTML page. I just want all the images from a single string.
On a page, I'm using two different strings. I want all the images that are within the second image. I want to loop them into a carousel.
I've looked around a bit and this is what I got:
function GetImgString($plaatje){
preg_match_all('/<img[^>]+>/i',$plaatje, $result);
$house = $result[0];
$i = 1;
$output = '<div class="carousel-inner">';
foreach ( $house as $houses ) {
if ($i == 1) {
$output.= '<div class="item active">';
}else{
$output.= '<div class="item">';
}
$output.=
$house.'
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
';
$i++;
}
$output .= '</div>';
return $house;}
This is the output:
Array
(
[0] => &ltimg src="images/Huizen/huis-3.jpg" alt="" />
[1] => &ltimg src="images/Huizen/huis-4.jpg" alt="" />
)
How do I solve this?
I assume, when you do the regexp, in your results, there are the 2 images.
You are start to building your output into a variable, calles $output, but you return with $house, what contain the 2 result from preg_match.
So you can try with this:
function GetImgString($plaatje) {
preg_match_all('/<img[^>]+>/i', $plaatje, $result);
$houses = $result[0];
$houses = str_ireplace('<', '&lt', $house);
$houses = str_ireplace('>', '&gt', $house);
$i = 1;
$output = '<div class="carousel-inner">';
foreach ($houses as $house) {
$class = ' class="item"';
if ($i === 1) {
$class = ' class="item active"';
}
$output.= '<div '.$class.'>';
$output.= $house . '
<div class="container">
<div class="carousel-caption"></div>
</div>
</div>' . "\n";
$i++;
}
$output .= '</div>';
return $output;
}

wordpress ignores formatting when using template tags in functions.php

I am using the following code to create a shortcode for use in the WYSIWYG.
function consultants( $atts, $content = null ) {
$output = '';
$consultant_query = new WP_Query('post_type=consultants&showposts=10');
if ($consultant_query->have_posts()) :
$output .= '<div class="col-md-12">';
while ($consultant_query->have_posts()) : $consultant_query->the_post();
$output .= '<div class="col-xs-12 col-sm-5 col-md-4 kam-tile-own-bg"><h1>' .the_title(). '</h1> ';
if(has_post_thumbnail())
{
$output .= get_the_post_thumbnail($post->ID,'wpbs-featured-avatar');
} else {
$output .= '
<img class="kam-avatar" width="62" height="62" src="'.get_template_directory_uri().'/images/avatar#2x.jpg" class="attachment-featured_image wp-post-image" alt="" />'; }
$output .= '</div>';
endwhile;
$output .= '</div>';
endif;
wp_reset_postdata();
return $output;
}
The code works fine - HOWEVER it fails on the .the_title(). it throws this at the top of the page it has no respect for the tags or the in which it is contained.
Many thanks
instead of the_title(); use get_the_title();

adding for each clause into variable

I have the following variable $prod_list_contents which is a mix of html and php METHODS to display the products from my database:
$prod_list_contents .= '<div style="width:100%;">';
$prod_list_contents .= '';
while ($listing = tep_db_fetch_array($listing_query)) {
$rows++;
$prod_list_contents .= '
<div class="cat_prod_box">
<div class="image">
<div class="cat_image_table">
<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) . '">' . tep_image(DIR_WS_IMAGES_CAT . $listing['products_image'], $listing['products_name'], 255, 340, 'class="cat_image_round"') . '
<div class="hidden_thing">Click to View</div>
</a>
</div>
</div>
<div class="cat_product_info" >';
$prod_list_contents .= '<div class="span_style_num">Style: '. $listing['products_model'] . '</div>';
$prod_list_contents .= '<div class="span_colors">Colors: red, blue</div>';
$prod_list_contents .= '<div class="span_product_name">' . $listing['products_name'] . '</div>';
$prod_list_contents .= '<div class="span_price">CAD ' .$currencies->display_price($listing['products_price'], tep_get_tax_rate($listing['products_tax_class_id'])) .'</div>' ;
$prod_list_contents .= '</div></div>';
}
$prod_list_contents .= ' </div>' .
' '
;
echo $prod_list_contents;
I am trying to incorporate a color table into the same div that is being displayed through this same variable. My color table is derived through the following bit of php:
<div >
<?php
$ctr = 0;
$clr=1;
foreach($products_options_array as $products_options_array2) {
$ctr++;
//if it is a color image, or a color hex
if($products_options_array2['color_image']!='')
{
$clr_sec = "style=\"background-image:url(images/pattern/".$products_options_array2['color_image'].") !important; height:28px; width:28px;\"" . "class=\"testy\"";
}
else {
$clr_sec = "style=\"background-color:".$products_options_array2['color_code']." !important; height:28px; width:28px;float:left;\"" . "class=\"testy\"";
}
?>
<div <?php echo $clr_sec;?>> </div>
<?php
$clr++;
} ?>
</div>
I have tried adding it into the prod_list_contents variable but I don't think I can because of the php here is not METHODS. and requires semi colons etc. Is there another way to go about this? Or am I able to add it in and I'm just being stupid?
If i understand your question correctly you wan to add $clr_sec to $prod_list_contents.
Just change
<div <?php echo $clr_sec;?>> </div>
to
$prod_list_contents.='<div '.$clr_sec.'</div>';

Categories