I have been trying to loop nested foreach loops but the problem is first foreach loop records repeating as the count of second foreach loop
first array is coming from mysql data and second array I have wrote below, In my case i want to loop the color presets in second array with first foreach loop results. I'm not much good in arrays please help me to solve this issue.
here is the second array and code :
$colors = array (
0 => array ("id"=> 0, "dark" => "#16a085", "light" => "#1ABC9C"),
1 => array ("id"=> 1, "dark" => "#2980B9", "light" => "#3498DB "),
);
$unique = array_unique($colors, SORT_REGULAR);
foreach ($skill as $skilldata) {
foreach ($unique as $key => $val) {
<div class="skillbar clearfix " data-percent="<?php echo $skilldata['js_skill_perc'].'%'; ?>">
<div class="skillbar-title" style="background: <?php echo $val['dark']?>;">
<span><?php echo $skilldata['js_skill_title']; ?></span></div>
<div class="skillbar-bar" style="background-color: <?php echo $val['light']?>; width: <?php echo $skilldata['js_skill_perc'].'%'; ?>;"></div>
<div class="skill-bar-percent"><?php echo $skilldata['js_skill_perc'].'%'; ?></div>
</div>
<?php }} ?>
Output should be like : HTML5 (green) PHP(blue) and SEO (green)
but this is how output looks like:
If You need to just switch the colors from line to line, You can use CSS for this (see :nth-child(even) and :nth-child(odd)) or do it in PHP like this:
$colors = array(
...
);
$colors_count = count($colors);
$colors_index = 0;
foreach ($skill as $skilldata) {
$color = $colors[$colors_index % $colors_count];
$colors_index++;
echo ... whatever using $color ...
}
Related
I have a list of 6 products that i want to split in 2 lists of 3 products next to each other. The list are made within a foreach loop, the first list stops after the count == 2, so 3 items wil be displayed. The second list should start with the fourth item. How can i achieve this?
This is wat makes the first list of 3 items:
<?php
$_categoryId = explode(' ', $category['id']);
$count = 0;
$_productCollection = Mage::getModel('catalog/category')->load($_categoryId)
->getProductCollection()
->addAttributeToSelect('*')
->setOrder('date_added', 'DESC');
?>
<?php foreach ($_productCollection as $_product): ?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php
if($count == 2) break; // Stop after 3 items
$count++;
?>
<?php endforeach ?>
Best regards,
Robert
For simplicity you could repeat the foreach statement but doing the opposite and continue on the first three items.
<?php foreach ($_productCollection as $_product): ?>
<?php
$count++; // Note that first iteration is $count = 1 not 0 here.
if($count <= 3) continue; // Skip the iteration unless 4th or above.
?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php endforeach ?>
The keyword continue is used in loops to skip the current iteration without exiting the loop, in this case it makes PHP go directly back to the first line of the foreach-statement, thus increasing counter to 4 (since 4th, 5th and 6th is what we're after) before passing the if statement.
Commentary on the approach
I kept it coherent with your existing solution but a more clean way in this case would probably be to use the built in Collection Pagination.
If you use ->setPageSize(3) you can simply iterate the collection to get the first three products and then use ->setCurPage(2) to get the second page of three items.
I'm linking this blog post on the topic here just to give you an example of how it's used but since I don't know your comfort level in working with collections I retain my first answer based on your existing code.
Something like that with modulo function for have new array each 3 items :
$count = 1;
$count_change = 1;
$key = 0;
$yourList = array(
"1",
"2",
"3",
"4",
"5",
"6",
);
foreach ($yourList as $item) {
if (!isset($$new_list)) {
$new_list = "list" . $count_change . "";
$$new_list = array();
}
if ($count % 3 == 0) {
$key = 0;
$count_change++;
$new_list = "list" . $count_change . "";
$$new_list = array();
}
$$new_list[$key] = $item;
$count++;
$key++;
}
Hope this helps.
I know this has been posted a million times over but I cant find an example where the same item was being called for the same use but with different values. I am using lightbox and I need my <a> to pull in the size=full and my <img> to pull in the size=thumbnail. I am successfully doing this but my nested foreach statements are casing duplicates.
<?php
$dyno_images = rwmb_meta( 'gallery-images', 'type=image_advanced&size=thumbnail' );
$dyno_images_lrg = rwmb_meta( 'gallery-images', 'type=plupload_image&size=full' );
?>
<?php
foreach ( $dyno_images_lrg as $dyno_image_lrg ) {
foreach ( $dyno_images as $dyno_image ) {
echo '<figure class="gallery-item"><div class="gallery-icon landscape"><img src="'.$dyno_image['url'].'" aria-describedby="gallery-1-584" class="attachment-full"></div></figure>';
}
}
?>
I assume that each item in $dyno_images_lrg corresponds to an item in $dyno_images.
In that case you only want to loop once and pick out the corresponding item:
foreach ( $dyno_images_lrg as $key => $dyno_image_lrg ) {
$dyno_image = $dyno_images[$key];
//Snipped for brevity - rest of the code should remain the same
}
I was wondering if anyone could give me a hand with this...
Basically I am trying to modernize the news system of my site but I can't seem to limit the amount of posts showing in the foreach loop that is on my blog part of the site. I need to skip the first instance as it is already promoted at the top of the page. I've tried various google searches but im getting results for C++ Perl and python, what is really irritating. I just need a simple PHP solution. I'll pop my code below and see if anyone can help. Thanks for any help in-advance. And please remember to leave your responses as an answer so I can mark them up if they helped ;)
<div class="view22 full" style="margin-top:0;">
<h3>Recent News and Announcements</h3>
<?php foreach ($articles as $article) {
?>
<div class="ah7_ clearfix">
<p class="date"><?php echo date('F j', $article['article_timestamp']); ?>, <?php echo date('Y', $article['article_timestamp']); ?></p>
<h3><?php echo $article['article_title']; ?></h3>
</div>
<?php
}
?>
</div>
I assume that the $articles array has keys starting with 0. How about modifying the loop like this:
foreach ($articles as $key => $article)
and checking if $key is 0 at the beginning?
if($key == 0)
continue;
If the array keys are different: Create a new variable $i, set it to 0 and increase the value by 1 in every foreach loop iteration.
$i = 0;
foreach ($articles as $article) {
$i++;
if($i == 1)
continue;
elseif($i > 8)
break;
//the other code goes here
}
In case it is based on a SQL query, using "limit" might help to reduce load!
There are a few things you can do:
If you $articles is an array of array, having continous indexes, use a for loop instead of foreach and do something like
for ($i = 1; $i < 8 : $i++ ) {
// and access it like
$articles[$i]['some_index'] ...
}
If it is not then you can use an external counter
Say
$counter = -1;
foreach ( $articles as $article) {
$counter++;
if (!$counter) continue;
if ($counter > 7 ) break;
...// your code //
}
You can change your Mysql query to give you only the desired data, using LIMIT and OFFSET
To remove the first instance you can manually unset the item ($articles[0]) after making a copy of it or printing it as a featured news.
To limit the number of post you can use the mysql LIMIT Clause;
Or you can do something like this
foreach($articles as $key => $article){
if($key===0)
continue;
if($key===8)
break;
echo $article;// or_do_whatever_youwant_with($article);
}
I have a $row array that will print the below array
Array
(
[BookCode] => 124
[BookName] => Book1
)
Array
(
[BookCode] => 123
[BookName] => Book2
)
...........
I have a code like this:
<?php foreach($row as $key=>$value){ ?>
<span style="color:red;font-weight:bold;"><?php echo $value; ?></span>
<?php } ?>
But I'm not able to get the BookCode in my anchor tag since I'm using foreach with key-value. In my case I have to use foreach only (as intructed by my client)
So how can I get the value inside the anchor tag?
Your foreach loop is not returning what you expect—you have an array of associative arrays.
<? foreach ( $row as $column ): ?>
<a href="process.php?bcode=<?=$column['BookCode']?>">
<? endforeach; ?>
In the above, the link will be process.php?bcode=124
Alternatively, if you really want to use the $key=>$value:
<? foreach ( $row as $column ): ?>
<? foreach ( $column as $key=>$value ) ?> // here $key = 'BookCode'
<a href="process.php?bcode=<?=$value?>">
<? endforeach; ?>
<? endforeach; ?>
Try foreach like this. It may help to you
foreach($row as $data)
{?>
<?php } ?>
I am working with SimplePie and I cannot figure out how to output the count, or the key values for the loop.
Shouldn't this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = key($item);
echo $i;
?>
<?php endforeach; ?>
, or this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = count($item);
echo $i;
?>
<?php endforeach; ?>
be outputting a unique number for each?
uniqid() Doesn't work in this case, because I am running the loop twice on the page and trying to match up one list of elements with another based on ID.
A single argument used with as is interpreted as a variable in which to store the value, not the key. If you want the key, you need to use => in a manner like the following:
foreach ($feed->get_items() as $key => $item):
echo $key;
endforeach
As a sidenote, you're using key() and count() on an item in the array, rather than the array as a whole, which is invalid. As far as I'm aware, there's no guarantee that key() will work as you expect even if applied to the whole array. It's meant for loops where you control the iteration, as with next.
To get the 'count' in a foreach you would need an extra variable. Getting the key is easy and the same if the array is indexed in order instead of associative. Here is an example including both:
$array = array(
'foo' => 'bar'
);
$i = 0;
foreach ($array as $key => $value)
{
/*
code where $i is the 'count' (index) and $key is the associative $key.
*/
/* $i == 0 */
/* $key == 'foo' */
/* $value == 'bar' */
$i++;
}
key($item) that you're using above doesn't work because you're trying to get the key of a value that no longer is associated with the original array.
count($item) is the count of a subarray $item.
you can use get_id() method
like :
foreach ($feed->get_items() as $item)
{
$prev_ids = array('guid1', 'guid2', 'guid3', 'guid4');
if (in_array($item->get_id(true), $prev_ids))
{
echo "This item is already stored.";
}
else
{
echo "This is a new item!";
}
}