Reputation: 119
I am having trouble creating a solution that will target the end row of a MySQL query. Currently I have a foreach function that works through the query and displays each one as a div with the information inside:
<?php $residents = Resident::find_all();
foreach($residents as $resident): ?>
<div class="submenu">
<p class="menuitem submenuheader"><?php echo $resident->name; ?></p>
<img src="images/<?php echo $resident->image_path(); ?>" width="250" class="image" />
<p><?php echo $resident->info; ?></p>
</div>
.submenu currently has a bottom border. I need to remove this on the last row returned. I have looked at DESC LIMIT 1, however this requires another MySQL query and could make things very messy...
Upvotes: 2
Views: 212
Reputation: 15892
If you separate your HTML and PHP a little this is easily achieved:
<?php
function echoBlock($resident,$pClass="menuitem submenuheader") {
echo "<div class=\"submenu\">\n<p class=\"$pClass\">\n";
echo $resident->name;
echo "</p>\n<img src=\"images/";
echo $resident->image_path();
echo "\" width=\"250\" class=\"image\" />\n<p>";
echo $resident->info;
echo "</p>\n</div>\n\n";
}
$residents = Resident::find_all();
$last=count($residents)-1;//2 element array last pos is 1
for ($i=0;$i<$last;$i++) {
echoBlock($residents[$i]);
}
echoBlock($residents[$last],"menuitem");
?>
echoBlock
(which could easily be a method on a class) requires the calling code to know about the classes it uses, which isn't really separating intent but it does prevent the need for an if
branch on every loop. That being said it would be less efficient but perhaps more usable to set it up as:
function echoBlock($resident,$isLast=false) {
$pClass="menuitem".($isLast?"":" submenuheader");
//...
Which then doesn't need the caller to know anything about what echoBlock
does.
Upvotes: 1
Reputation: 3345
What about
Instead of echo'ing each line one by one, create one big string in PHP, search for the last entry of "submenu" and change the class.
Upvotes: 0
Reputation: 14814
You could switch to putting the border on the top of the element, and use the :first-child
pseudo selector in CSS to remove it.
http://reference.sitepoint.com/css/pseudoclass-firstchild
The :last-child
selector would be nice, but it's not supported in IE before version 9, so it's not a good idea to use it if you want compatibility.
Upvotes: 1
Reputation: 1828
You could try and pop
the array using array_pop()
, to get the last value out of the array and then inputing it using the special class after the foreach loop.
Upvotes: 0
Reputation: 71918
Addd this to your CSS:
.submenu:last-child { border-bottom: 0; }
Note: this is not supported by IE < 9.
Upvotes: 2