Group these records by groupId in a separate div

Discussion in 'PHP' started by Kinaski, Feb 9, 2009.

  1. #1
    Hi Folks, I really hope that someone out there can help me..

    Here is my problem:

    I'm trying to setup my site using joomla, but had to dig into the code to make some modifications myself.

    I have a component where I display some categories with links to articles like this:
    
    <?php foreach($this->list as $l): ?>
      <li class="article-intro-list">
        <h3 class="article-title"><a href="<?php echo $l->link; ?>" ><?php echo $l->title; ?></a><span>+</span></h3>
        <div class="collapse"> <?php echo $l->description; ?>
          <div class="loadPopUp"><a href="<?php echo $l->link; ?>" title="<?php echo $l->title; ?>" class="mb" rel="width:730,height:500"><span class="howdoi_icon"><img src="images/more.gif" alt="Read more" /></span> Read more...</a></div>
        </div>
      </li>
       <?php endforeach; ?>
    
    PHP:
    What this list array contains is also a reference to a groupId of the category, which can be retrieved simply by:
    <?php echo $l->groupId; ?>
    PHP:
    And also the group title by:
    <?php echo $l->groupTitle; ?>
    PHP:
    I would like to group these categories by their groupId into a separate div with a title for each group.
    I really can't figure out that... although it seems pretty straightforward... Still not so good in php :(

    Thanks so much in advance!
     
    Kinaski, Feb 9, 2009 IP
  2. steelaz

    steelaz Peon

    Messages:
    47
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    There may be a better way to do it, but this was my first though:

    
    // Generate groups array where array key is groupId
    $groups = array();
    foreach ($this->list as $l) $groups[$l->groupId][] = $l;
    
    // Go through groups array, use first record in array to fetch group title
    foreach ($groups as $group)
    {
    	echo '<div><b>'.$group[0]->groupTitle.':</b> ';
    	foreach ($group as $item) echo $item->title .' ';
    	echo '</div>';
    }
    
    PHP:
     
    steelaz, Feb 9, 2009 IP