Jump to content


Photo

Sort within a foreach loop

loop foreach sort

  • Please log in to reply
2 replies to this topic

#1 onjegolders

onjegolders

    Hero Member

  • Members
  • PipPipPipPipPip
  • 827 posts
  • 217

  • LocationMidlands, UK

Posted 09 April 2012 - 07:41 AM

I'm having a few issues trying to sort from within a loop.

$blog_entry = $page->children("sort=title");
  foreach ($blog_entry as $entry)
 
   {
    // add classes to first and last boxes.
    $class = 'blog_box';
    if ($blog_entry->getItemKey($entry) % 2) {$class .= ' blog_box_even';}
    if ($entry == $page->children->first()) {$class .= ' blog_box_first';}
    elseif ($entry == $page->children->last()) {$class .= ' blog_box_last';}
    else { $class .= ''; }
    // make blog images 200 X 150
    $image = $entry->single_image;
	  echo "<div class='$class'>";
	  echo "<div class='blog_text'>";
	  echo "<h3>$entry->title</h3>";
	  if (!empty($entry->summary)) {
			  echo "<p>$entry->summary</p>";
		    }
		    else {
			  echo "<p>$entry->body</p>";
		    }
	  echo "</div><!-- /.blog_text -->";
	  echo "<img src='$image->url' width='200' height='150' alt='alt text' class='small_frame' />";
	  echo "<div class='clear'></div>";
	  echo "</div><!-- /.blog_box -->";
  }

If i do the above and sort before the loop, the data gets sorted but it messes up my classes which are added in the logic within the loop.

Where can I add the sort parameter to to sort from within? Everything I've tried hasn't worked unfortunately.

Thanks

#2 Soma

Soma

    Hero Member

  • Moderators
  • 3,403 posts
  • 1933

  • LocationSH, Switzerland

Posted 09 April 2012 - 07:55 AM

it will work just change it to this.


...
if ($blog_entry->getItemKey($entry) % 2) {$class .= ' blog_box_even';}
if ($entry == $blog_entry->first()) {$class .= ' blog_box_first';}
elseif ($entry == $blog_entry->last()) {$class .= ' blog_box_last';}
...

@somartist | modules created | support me, flattr my work flattr.com


#3 onjegolders

onjegolders

    Hero Member

  • Members
  • PipPipPipPipPip
  • 827 posts
  • 217

  • LocationMidlands, UK

Posted 09 April 2012 - 08:10 AM

it will work just change it to this.


...
if ($blog_entry->getItemKey($entry) % 2) {$class .= ' blog_box_even';}
if ($entry == $blog_entry->first()) {$class .= ' blog_box_first';}
elseif ($entry == blog_entry->last()) {$class .= ' blog_box_last';}
...


You're right, thanks Soma!
I just added in a $ to blog_entry.
Am still getting confused with my basic PHP.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users