How can I loop this PHP code for six times exactly? - php

OK, this is my code:
<?php if (!empty($projectSectorItem1Title)): ?>
<div class="project" style="overflow:hidden;">
<?php if (!empty($projectSectorItem1Image)) { ?>
<img src="<?php echo $projectSectorItem1Image; ?>" width="100%"/>
<div class="project_box_info">
<h3><a><?php echo $projectSectorItem1Title; ?></a></h3>
<p><?php echo $projectSectorItem1Description; ?></p>
</div>
<?php } else { ?>
<div class="project_box_info" style="opacity:1;">
<h3><a><?php echo $projectSectorItem1Title; ?></a></h3>
<p><?php echo $projectSectorItem1Description; ?></p>
</div>
<?php } ?>
</div>
<?php endif; ?>
This code is repeated currently in my .php file six times, as I have up to six items. If the first if statement returns false, naturally nothing appears. This is good. It works. However, I've noticed my page is loading slower now with six of these stacked up on each other.
Is there a way to systematically loop this exact code for each of the numbers? The only thing that would need to change is the numbers.. i.e. above #1, second #2, third #2 etc. Lines containing numbers that need to increase are: 1, 3, 4, 6, 7, 11, 12. So there are 7 places. I have no idea how to do this!
I have a similar issue in the same .php file, but if I know how to do this one, I should be able to "kill two birds with one stone" as they say. Many thanks for any help.
To clarify what I'm trying to do for one of the commenters: I have six boxes which are associated with meta data for each item inside each box. If the title variable is filled in, we go ahead with the rest of the code. However, if there is no image, there is no "hover" feature; instead, the opacity of the hover box is already filled (hence that opacity:1; in the second bit).
So... check for title > if title exists, go ahead > if image, proceed as normal but if not > proceed as normal without the image and set opacity to 1 for project_box_info
Really I'm just reiterating the code here in English, but that's all I can do really!

You can use a forloop like below
<?php for($i=1;$i<=6;$i++): ?>
<?php if (!empty(${"projectSectorItem{$i}Title"})): ?>
<div class="project" style="overflow:hidden;">
<?php if (!empty(${"projectSectorItem{$i}Image"})) { ?>
<img src="<?php echo ${"projectSectorItem{$i}Image"}; ?>" width="100%"/>
<div class="project_box_info">
<h3><a><?php echo ${"projectSectorItem{$i}Title"}; ?></a></h3>
<p><?php echo ${"projectSectorItem{$i}Description"}; ?></p>
</div>
<?php } else { ?>
<div class="project_box_info" style="opacity:1;">
<h3><a><?php echo ${"projectSectorItem{$i}Title"}; ?></a></h3>
<p><?php echo ${"projectSectorItem{$i}Description"}; ?></p>
</div>
<?php } ?>
</div>
<?php endif; ?>
<?php endfor; ?>
That is your loop.. Feel free to ask any questions.

You would use a for loop;
<?
for (int i = 0; i < 6; i++) {
// your code here
}
This would loop through the above statement 6 times. If you want to change a number, you could substitute in for i - (or i+1);
<?
for (int i = 0; i < 3; i++) {
echo("this is cycle number $i");
}
Would return with;
this is cycle 0
this is cycle 1
this is cycle 2

I believe you're looking for something along these lines.
Having an array of items with set titles, descriptions and image urls should greatly increase the execution speed. Then, as others have suggested, loop over the array with a for or foreach.
Using this method better separates the data from the presentation, which makes the whole thing easier to read and modify.
$items = array(
array(
'title' => 'Item 1',
'description' => 'This is the description for item1',
'image' => 'http://fake.com/images/item1.png'
),
array(
'title' => 'Item 2',
'description' => 'This is the description for item2',
'image' => 'http://fake.com/images/item2.png'
),
array(
'title' => 'Item 3',
'description' => 'This is the description for item3'
),
array(
'title' => 'Item 4',
'description' => 'This is the description for item4',
'image' => 'http://fake.com/images/item4.png'
),
array(
'title' => 'Item 5',
'description' => 'This is the description for item5',
'image' => 'http://fake.com/images/item5.png'
),
array(
'title' => 'Item 6',
'description' => 'This is the description for item6'
)
)
foreach ($items as $item) {
echo '
<div class="project">
', (isset($item['image']) ? '<img src=' . $item['image'] . '" alt="" />' : ''), '
<div class="project_box_info">
<h3><a>', $item['title'], '"</a></h3>
<p>', $item['description'], '"</p>
</div>
</div>';
}
I did omit your inline styles here for the sake of readability. Really they should be in an external stylesheet anyway.

Related

How to loop php variables?

I have a list of variables like this:
<?php
$hh_1_date="Aug 29, 2012";
$hh_1_title="Data 1";
$hh_1_video="FFFnQGX0";
$hh_1_name="Peter Pan";
$hh_1_company="CompTIA";
$hh_1_image="image1.png";
$hh_1_date="Aug 30, 2012";
$hh_1_title="Data 2";
$hh_1_video="FFFRDEX0";
$hh_1_name="Peter Pooh";
$hh_1_company="CompTIA";
$hh_1_image="image2.png";
?>
And then I pull those variables into markup like this - all basic stuff...
<div class="card">
<img alt="..." class="card-img-top" src="<?php echo $hh_1_image?>">
<div class="card-body">
<span class="badge badge-pill badge-dark"><?php echo $hh_1_date ?></span>
<h5 style="color:#0c0c0e"><?php echo $hh_1_title ?></h5>
</div>
</div>
But at the moment I am copying and pasting the above HTML and changing the PHP to _2 then _3 then _4 according to its respective PHP Variable which I know is the wrong way of doing it.
So, what is a faster way? I believe it's called looping?
Thanks
Put all these variables in array with key value pair and use foreach loop, like this:
$arr =[
[
'date' =>'Aug 30, 2012',
'title' => 'Data 1',
'video' => 'FFFRDEX0',
'name' => 'Peter Pooh',
'company' => 'CompTIA',
'image' => 'image1.png'
],
[
'date' =>'Aug 29, 2012',
'title' => 'Data 2',
'video' => 'FFFRDEX0',
'name' => 'Peter Pooh',
'company' => 'CompTIA',
'image' => 'image2.png'
]
....
.....
......
]
<?php foreach($arr as $k => $v): ?>
<div class="card">
<img alt="..." class="card-img-top" src="<?php echo $v['image']">
<div class="card-body">
<span class="badge badge-pill badge-dark"><?php echo $v['date'] ?></span>
<h5 style="color:#0c0c0e"><?php echo $v['title'] ?></h5>
</div>
</div>
<?php endforeach; ?>
You can use the get_defined_vars (Here is the docs) function. Here is an example.
<?php
$hh_1_date="Aug 29, 2012";
$hh_1_title="Data 1";
$hh_1_video="FFFnQGX0";
$hh_1_name="Peter Pan";
$hh_1_company="CompTIA";
$hh_1_image="image1.png";
$hh_1_date="Aug 30, 2012";
$hh_1_title="Data 2";
$hh_1_video="FFFRDEX0";
$hh_1_name="Peter Pooh";
$hh_1_company="CompTIA";
$hh_1_image="image2.png";
$vars = get_defined_vars();
foreach($vars as $key => $val){
print_r($val);
}
?>
While iterating through, You'll get the variable name as key and variable's value as the value in a loop. Be careful, This method will also return the global variables defined by PHP(e.g $_SERVER, $_POST etc). The function get_defined_vars returns all the variables available in current scope along with it's value.

How to loop data from multidimensional arrays in PHP and inject it into HTML

I'm fairly new to PHP and still struggling with the simplest of tasks. I have searched the internet but could not find or figure out the right solution.
Let's say that I've got two pages: one is index.php, where I want to display a list of hyperlinks and names of respective pages those links lead to. The other is functions.php, where I've stored an array containing my links and titles. Also, I'm aware that arrays could be stored in a better place than functions.php, but that's beside the point, for now.
This is my HTML on the index.php page:
<ul class="row">
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
</ul>
This is my array:
$pageitems = array (
array('link' => 'https://website-one.com', 'title' => 'Website 1'),
array('link' => 'https://website-two.com', 'title' => 'Website 2'),
array('link' => 'https://website-three.com', 'title' => 'Website 3'),
);
And this is my function that I hoped would loop through each sub-array and display the link and title in the page items on the index.php page:
$i = 0;
foreach ( $pageitems as $pageitem ) {
$i++;
foreach ( $pageitem as $key => $value )
{
return $pageitem['link'];
return $pageitem['title'];
}
}
But no - it only repeats the first link and title pair (website-one.com, Website 1) on every page item on the index page, like the loop gets stuck after the first iteration.
I guess you have to iterate the array you have and put the li inside a foreach loop, like this:
<ul class="row">
<?php
$pageitems = array (
array('link' => 'https://website-one.com', 'title' => 'Website 1'),
array('link' => 'https://website-two.com', 'title' => 'Website 2'),
array('link' => 'https://website-three.com', 'title' => 'Website 3'),
);
foreach ($pageitems as $pageitem) {
?>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<?php
}
?>
</ul>
If it's better for you to have the $pageitems in a different file, you can use include('function.php'); any point before the foreach loop.

MySQL to PHP output HTML with grouped content (categories)

i have problem that i googled allot to try and figure out, but all solutions are variations on mine.
So i have output like this
<div class="row">
<?php $cat= '';?>
<div class="blank">
#foreach($posts as $post)
#if($cat!= $post->cat_id)
</div><div class="col-sm-3">
<p class="alert alert-info"><strong>{{$post->category_name}}</strong></p>
<?php $cat= $post->cat_id; ?>
#endif
</ul><ul>
<li>
{{$post->title}}
</li>
#endforeach
So basically i wont output that category name is in and then all the posts of that category within that div in ul li, and then close the DIV.
But i managed to make it only with this blank div, and closing ul and div before open, but that gives me invalid html, but its sorted good.
Is there any smart way to get this done?
Thanks
here is a working example. I think the problem was the place where you were opening and closing the foreach.
...
(I replaced the blade statements for plain php for clarity, but you should be able to change it back.)
EDIT:
I was not that far..
<?php $posts = [
['cat_id' => 1, 'cat_name' => 'a name', 'title' => 'title'],
['cat_id' => 1, 'cat_name' => 'a name2', 'title' => 'title2'],
['cat_id' => 2, 'cat_name' => 'another name', 'title' => 'title3'],
['cat_id' => 2, 'cat_name' => 'another name2', 'title' => 'title4'],
]; ?>
<div class="col-sm-3">
<?php $cat= '';?>
<?php foreach($posts as $post): ?>
<?php if($post['cat_id'] != $cat): ?>
<p class="alert alert-info">
<strong><?php echo $post['cat_name'];?></strong>
</p>
<ul>
<?php endif; ?>
<li> <?=$post['cat_name'];?> </li>
<?php if($post['cat_id'] == $cat): ?>
</ul>
<?php endif; ?>
<?php $cat= $post['cat_id']; ?>
<?php endforeach; ?>
</div>
Here I edited my previous answer, a few recommendations tho:
The point is not to just write code that works, but also maintainable and readable. That will help you or whoever has to change some functionality in the future.
Try to be as clear as you can be when asking, and provide an example of your desired output if needed (just like in the comment).
You could probably format the data before passing it to the view, so you can print it easily, for example, transforming the array I used in the above code to something like:
$posts = [
['cat_id' => 1, 'cat_name' => 'a name', 'posts' => [
['title' => 'a title','content' => 'whatever'],
['title' => 'another title','content' => 'whatever2'],
]
];
That way it would be waaay easier to show it, and it'll give you ways to
write clearer code.
Best regards!
So after extensive trying, i got what i wanted. Hope this is correct way of doing it.
<?php
$cat= '';
foreach($posts as $post){
if($cat != $post['cat_id']){
echo $cat!= '' ? '</ul></div>' : '';
echo '<div class="col-sm-4 col-md-3">
<p class="alert alert-info"><strong>'.$post['cat_name'].'</strong></p>
<ul>';
$cat= $post['cat_id'];
}
echo '<li>'.$post['title'].'</li>';
}
echo '</ul>'; //close last opened ul
echo '</div>'; //close last opened div
?>

How to get in php foreach value from other array?

I get images in a array then i read it with a foreach this are images, but how can i get also image text, my example is here:
$slideImages = array('image/path/image1', 'image/path/image2', 'image/path/image13');
$slideText = array('image text 1', 'image text 2', 'image text 3');
if($slideImages) :
echo '<ul>';
foreach($slideImages as $slideImage) :
?>
<li>
<div>IMAGE TEXT</div>
<img src="<?php echo $slideImage; ?>" />
</li>
<?php
endforeach;
echo '</ul>';
endif;
I need to embed also image text from the true position, i know how to do it with for but so is not efficient... it's something like this possible?
Assuming the keys are the same, use the $key in the foreach:
foreach($slideImages as $key => $slideImage) :
?>
<li>
<div>IMAGE TEXT</div>
<img src="<?php echo $slideImage; ?>" />
<?php echo $slideText[$key]; ?>
</li>
<?php
endforeach;
You could also change the way you store the info and keep them in one multidimensional array.
$slides = array(
array( image => "image/path/image1", text => "image text 1"),
array( image => "image/path/image2", text => "image text 2"),
array( image => "image/path/image3", text => "image text 3")
);
Then you would iterate through the $slides array and just pull out the image and text for each:
foreach($slides as $slide)
{
echo "Text:".$slide["text"];
echo "Image Path:".$slide["image"];
}
This organizes your code a little better so you don't wind up with something crazy going on should your two arrays wind up out of sync.
simplified example:
foreach($slideImages as $key=>$var){
echo $var;
echo $slideText[$key];
}

getting resized product pictures without loading product

Regarding the poor performances of my magento homepage (4 seconds computing before it start loading assets) i optimized my source code to go down to 1 second, by removing all the $_product->load that were in my loops.
But i'm facing another issue, i can't call the picture this way anoymore :
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'image')->resize(135); ?>"
so, i began to call thumbnails
<?php echo Mage::getModel('catalog/product_media_config')->getMediaUrl($_product->getThumbnail()); ?>
but there's few points that annoys me, the 2nd call don't get a default placeholder picture if no picture is found, and the bigger problem is, all the magento's product have only a large res file, which is called if i don't upload a thumbnail for each product (note : i got 1600+ products, i'd like to avoid a manual upload for every single item)
So i have two options : getting th catalog/image helper to work without loading product, or finding a way to generate all the thumbnail with the high res pictures (i looked for an extension doing this, but i guess i'm a bad googler)
EDIT : here's the collection call
$selections_products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect(
array(
'name',
'special_from_date',
'special_to_date',
'thumbnail',
'image',
'couleur',
'special_price',
'url_path',
'price',
'format',
'selection_moment',
'selection_rouge',
'selection_blanc',
'selection_cdc',
'selection_champagne',
'selection_exception'
)
)
->addAttributeToFilter(array(array('attribute'=>'attribute_set_id', 'like' => '4')))
->addAttributeToFilter(
array(
array('attribute'=>'selection_moment', 'like' => '1'),
array('attribute'=>'selection_rouge', 'like' => '1'),
array('attribute'=>'selection_blanc', 'like' => '1'),
array('attribute'=>'selection_cdc', 'like' => '1'),
array('attribute'=>'selection_champagne', 'like' => '1'),
array('attribute'=>'selection_exception', 'like' => '1')
)
);
$selections_products->getSelect()->limit(32);
EDIT 2 : foreach on the collection :
<?php $i = 0;
foreach($selections_products_rouge as $_product): ?>
<?php if($i==0 || $i==4): ?>
<tr>
<?php endif; ?>
<td>
<div class="prod-resume">
<div class="thumb-wrapper">
<div class="thumb">
<div class="pic-holder">
<a href="<?php echo $_product->getProductUrl() ?>">
<img height="220" src="<?php echo Mage::getModel('catalog/product_media_config')->getMediaUrl($_product->getThumbnail()); ?>"/>
</a>
</div>
</div>
</div>
<h3 class="title"><?php echo $_product->getName(); ?></h3>
<div class="type">
<?php
$cats = $_product->getCategoryIds();
$j = 0;
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
if($_cat->getLevel() != 2 && $j < 2 && $_cat->getName() != 'Default Category'){
echo '<span>'.$_cat->getName().'</span>';
$j++;
}
}
$couleur = $_product->getResource()->getAttribute('couleur')->getFrontend()->getValue($_product);
$format = $_product->getResource()->getAttribute('format')->getFrontend()->getValue($_product);
echo '<span>'.$couleur.'</span>';
echo '<span>'.$format.'</span>';
?>
</div>
<?php echo get_promo_stamp($_product); ?>
<div class="bottom">
<?php echo get_product_price_html($_product,$_taxHelper,$_coreHelper); ?>
<div class="btns">
Fiche produit
<?php if($_product->isSaleable()): ?>
Ajouter au panier
<?php endif; ?>
</div>
</div>
Aperçu
</div>
</td>
<?php if($i==3 || $i==7): ?>
</tr>
<?php endif; ?>
<?php $i++;endforeach; ?>

Categories