object foreach loop iterate only even values - php

Basically I have a set of object values I want render in 2 separate html lists
I figure the simplest way to do this is by displaying evens only in one list, and odd only in the other
Here is the current code for displaying a single list
<ul>
<?php foreach ($values as $value) : ?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
</ul>

Try this:
<ul>
<?php
/* read the index key */
foreach ($values as $key => $value) :
/* skip the current element if it doesn't have an even index */
if($key % 2 == 1) continue;
?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>

You didn't specify if the array has integer index. So I use a separate index pivot. This will do.
$v=array();
$index = 1;
foreach ($values as $value){
$v[($index++)%2][]=$value->value;
}
list ($evens, $odds) = $v;
echo "<ul><li>".implode("</li><li>", $odds)."</li></ul>"; // show list of odds
echo "<ul><li>".implode("</li><li>", $evens)."</li></ul>"; // shows list of even

Related

PHP foreach loop skip first 3 items

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.

foreach loop inside two other loops php

I have a foreach loop within two other foreach loops. The third one should repeat only once, incrementing the value each time.
It contains the titles for 5 headers in an accordion:
$header_title = array(
'first_link_title',
'second_link_title',
'third_link_title',
'fourth_link_title',
'fifth_link_title',
);
I've tried with
<?php foreach( $header_title as $value): ?>
<?php echo $value;?>
<?php endforeach;?>
But the $value output on each header is
first_link_titlesecond_link_titlethird_link_titlefourth_link_titlefifth_link_title
The expected output should be
Header1 - first_link_title
Header2 - second_link_title
Header3 - third_link title
ecc...
The second loop displays the accordion itself and the first one has nothing to do with the accordion.
Ayy help is much appreciated.
$prefix = 'Header';
$index = 1;
foreach ($header_title as $title) {
echo $prefix . $index . ' - ' . $title . PHP_EOL;
$index ++;
}
I think, this foreach loop must be outside two other foreach loops, not within. In other words those two other foreach loops must be within this "header_title" loop

Unset not working in multiple foreach statements (PHP)

Can someone tell me what is wrong with this code :
foreach ($data as $region ):
foreach ($region as $type):
foreach ($type as $type2):
foreach ($type2 as $key=>$val):
if ($val=='background-color: FFFFFF;' || $val=='') unset($type2[$key]);
endforeach;
endforeach;
endforeach;
endforeach;
After print_r($data) seems that the data array is the same and unset is not working
Your loop is operating on copies of the original elements; changes to $type2 will not be visible in $data because $type2 is a copy.
You can solve this by iterating over all arrays by key, then indexing into $data with those keys to remove the value:
foreach ($data as $k1 => $region ):
foreach ($region as $k2 => $type):
foreach ($type as $k3 => $type2):
foreach ($type2 as $k4 =>$val):
if ($val=='background-color: FFFFFF;' || $val=='') {
unset($data[$k1][$k2][$k3][$k4]);
}
endforeach;
endforeach;
endforeach;
endforeach;
Of course this is ugly, but that's four nested loops will do. There is also the option if iterating by reference instead of grabbing keys, but personally I dislike that because of the nice opportunity to write bugs by reusing the abandoned references after the loop has ended. Especially in this case I dislike it to the fourth power.
use this, it should work:
foreach ($data as &$region ):
foreach ($region as &$type):
foreach ($type as &$type2):
foreach ($type2 as $key=>$val):
if ($val=='background-color: FFFFFF;' || $val=='') unset($type2[$key]);
endforeach;
endforeach;
endforeach;
endforeach;
the array values are passed as reference because of the & i put before the value variables. The unset will work this way

How to get last key with values from array of arrays? PHP

This is what i am currently using
<?php $sidebar = $this->data['sidebar'];
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
if ($item['active']) { ?> class="active"<?php } ?>><?php echo htmlspecialchars($item['text']) ?></li>
<?php } ?>
This is what i get (http://pastebin.com/t6Y2ZtMF) when i print_r($sidebar);
I want to get the last Array which is Categories and turn it into links.
I am new to php, so my method could be wrong even though it works. I is there a right way to pull the Categories Array or the above code is good as it is?
$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()
After update:
You don't seem to be needing the key, only the array:
<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
Since you know you want the key 'Categories' though (not the last key), this seems the most logical thing to do:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
I think the end() function would be a great solution: http://php.net/manual/en/function.end.php
It basically returns the value of the last element in the array being passed to it.
$sidebar = end($sidebar);
If you want to get a key/value pair without popping & pushing the array, set the internal cursor to the end of the array and then use list and each to get the key & value.
// set up your array however you had it
$array = ...;
// move the cursor to the end of the array
end($array);
// use list() and each() to extract your key/value pair
list($key,$val) = each($array);
// $key will now have the last key
// $val will have the last value
perhaps, end:
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
You can use `end()` instead of `array_pop()`. But both works for the **last element** of the array. The only difference is `end()` **points out** the **last element** of the array without effecting it and `array_pop()` **pops** the element off the **end** of array.
Please go through the following links for detail information
end() | array_pop()

Outputting the count in a foreach function

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!";
}
}

Categories