I have the following code which displays related items in a wordpress template but I would like to add a class that every second item is attached with a css class of right, what do I need to modify to achieve this?
<?php $rel = $related->show(get_the_ID(), true);
foreach ($rel as $r) :
echo '<div class=related-item><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
endforeach;?>
Although this is Wordpress related I thought it was more related to general PHP coding so psoting here rather than at WPSE.
try this
<?php $rel = $related->show(get_the_ID(), true);
$count = 0;
foreach ($rel as $r) {
$class= ($count%2 == 0)?"right":"";
echo '<div class="related-item '.$class.'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
$count++;
}?>
If the array has a sequenced index you can use either a modulo calculation or a bitwise operation. If the array is based of non-numeric or not sequenced numbers you need to add a counter.
$i & 1 // odd using bitwise
$i % 2 // odd modulo
So what you would get is the following:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i % 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
Or using bitwise:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i & 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
Or if $rel has a zero based sequenced index:
foreach ($rel as $index => $r) { // note that I have used curly brackets. I think it is cleaner more standard
$classes = array('related-item');
if ($index & 2 == 1) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
<?php $rel = $related->show(get_the_ID(), true);
$i = 0;
foreach ($rel as $r) {
echo '<div class=related-item' . ($i++ % 2 ? '' : ' right') . '><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
?>
Something like this. My advice is to try to use curly braces instead of foreach () : endforeach;
Do you mean:
$i = 0;
foreach ($rel as $r) :
$class = (($i % 2) == 0) ? "your_class" : "";
echo '<div class="related-item $class"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.''.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
$i++;
endforeach;
<?php
foreach($rel as $key => $r) {
/* here we check if $key is even and assign class name or empty string to $class variable */
($key%2) ? $class = 'your-class-name' : $class = '';
/* and here we just add $class variable to 'class="related-items " part. */
/* so if $key is odd then $class will be empt and your div will have only 'related-item' class, and if $key is even then $class will hold 'your-class-name' value and div will have two classes: related-item and your-class-name */
echo '<div class="related-item '.$class.'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
?>
Related
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.
PHP to display feed items and list them alphabetically and display first letter of each title above. It is only show one letter above the whole list and it is the letter of the first title on the feed. I changed feedurl here for privacy purposes. Any Ideas?
<?php
$rss = new DOMDocument();
$feed = array();
$urlArray = array(array('url' => 'https://feeds.megaphone.fm/SH')
);
foreach ($urlArray as $url) {
$rss->load($url['url']);
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue
);
array_push($feed, $item);
}
}
usort( $feed, function ( $a, $b ) {
return strcmp($a['title'], $b['title']);
});
$previous = null;
foreach($item as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter)
$previous = $firstLetter;
}
$limit = 3000;
echo '<p>'.$firstLetter.'</p>';
echo '<ul style="list-style-type: none;>"';
for ($x = 0; $x < $limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo ''.$title.'';
echo '</li>';
}
echo '</ul>';
?>
Your foreach loop that determines the first letter of the title is outside the for loop that actually prints it. Therefore, you are always going to output the last letter of the foreach loop.
Move that part inside the for loop, something like
$limit = 3000;
$previous = null;
$count_firstletters = 0;
for ($x = 0; $x < $limit; $x++) {
$firstLetter = substr($feed[$x]['title'], 0, 1); // Getting the first letter from the Title you're going to print
if($previous !== $firstLetter) { // If the first letter is different from the previous one then output the letter and start the UL
if($count_firstletters != 0) {
echo '</ul>'; // Closing the previously open UL only if it's not the first time
}
echo '<p>'.$firstLetter.'</p>';
echo '<ul style="list-style-type: none;>"';
$previous = $firstLetter;
$count_firstletters ++;
}
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo ''.$title.'';
echo '</li>';
}
echo '</ul>'; // Close the last UL
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 :)
I cannot solve problem with starting ending divs after couple of elements from array.
What i want to get is something like that:
<div>
element1
element2
element3
element4
</div>
<div>
element5
element6
element7
element8
</div>
<div>
element9
element10
</div>
Here is my php code:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 1;
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 OR $count == 1){
echo '<div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
Try something like this
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 0;
echo '<div>';
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 && $count!=0){
echo '</div><div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
echo '</div>';
Okay I am not familiar with arrays and maybe something like this would work:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$i=0;
echo '<div>'
if (i<3) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>3 && $i<7) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>7 && $i<10) {
echo '$array[$i]';
$i++;
}
echo '</div>';
This might actually be a css question but I'm hoping not because I'd like this to work in IE.
I have the following loop:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
Which should output
item, item, item, item,
The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?
Well to keep your code how it is, you could add a counter, and skip the last one.
<?php
if ($category) {
$counter = 0;
foreach($category as $item)
{
$counter++;
echo $item['name'];
if ($counter < count($category)) {
echo ", ";
}
}
}
?>
Or you can do it much, much, quicker:
<?php echo implode(", ", array_map(create_function('$item', 'return $item["name"];'), $category)); ?>
Don't echo immediately but save your output into a variable that you can trim.
<?php
if ($category) {
$output = '';
foreach($category as $item) {
$output .= $item['name'];
$output .= ", ";
}
echo rtrim($output, ', ');
}
?>
The implode solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.
$myArray = array(); //Fill with whatever
$result = $myArray[0];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx];
}
EDIT: After realizing you want $item['name'] instead of just $item:
$myArray = array(); //Fill with whatever
$result = $myArray[0]['name'];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx]['name'];
}
As lovely as foreach is,...
<?php
if ($category) {
$count = count($category) - 1;
for ($i = 0; $i <= $count; $i++) {
echo $category[$i]['name'];
if ($i < $count)
echo ', ';
}
}
?>
...for is sometimes necessary.
Assuming $category is an array, you can use implode to get what you want:
Edit: Missed the $categories['name'] part, this should work:
<?php implode(", ", array_keys($category, 'name')); ?>
The standard solution to the "last comma" problem is to put items into an array and then implode it:
$temp = array();
foreach($category as $item)
$temp[] = $item['name'];
echo implode(', ', $temp);
If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:
function array_pluck($ary, $key) {
$r = array();
foreach($ary as $item)
$r[] = $item[$key];
return $r;
}
and then just
echo implode(', ', array_pluck($category, 'name'));
Or you could check for the last key:
end($category);
$lastkey = key($category);
foreach ( $category AS $key => $item ) {
echo $item['name'];
if ( $lastkey != $key ) {
echo ', ';
}
}
And another option:
<?php
$out = "";
foreach ($category as $item)
{
$out .= $item['name']. ", ";
}
$out = preg_replace("/(.*), $/", "$1", $out);
echo $out;
?>