0

I am currently creating a joomla component, and i am currently stuck with the menu part.

this is in my model file:

public function getMenu(){
    $menu_id = JRequest::getInt('id');

    $db = $this->getDbo();
    $query = $db->getQuery(true);

    $query->select('t.country_name,t.country_code, a.continent_name');
    $query->from('#__vectormap_countries AS t')
            ->join('LEFT', '#__vectormap_continents AS a USING(continent_id)')
            ->where('t.published = 1');

    $db->setQuery($query);

    $menu_items = $db->loadObjectList();

    return $menu_items;
}

and on the front end i have:

<?php  $menus = $this->menu ?>
<?php foreach($menus as $menu): ?>
    <div><?php echo $menu->continent_name ?></div>
    <li id="<?php echo $menu->country_code ?>"><?php echo $menu->country_name ?></li>
    <br />
<?php endforeach; ?>

and that returns:

Africa South Africa

Africa Mozambique or if i print out the array this:

Array ( [0] => stdClass Object ( [country_name] => South Africa [country_code] => ZA [continent_name] => Africa ) [1] => stdClass Object ( [country_name] => Mozambique [country_code] => MZ [continent_name] => Africa ) ) 1 

Now Finally the question, how would i sort it so that Africa (continent_name) not be repeated but rather have all the countries that have the continent_name of Africa list underneath it?

Keep in mind North America and such will also come in to play..

Summarized question -> How would I sort countries underneath there associated continents fond in the array.

Any Help Greatly Appreciated thanks.

how would i sort it that everything

1
  • 1
    Just a comment: dont mix different elements as children under an UL element (assuming your LI elements are part of an UL). Always use clean UL>LI syntax for browser consistency. Commented Apr 29, 2013 at 11:02

2 Answers 2

2

The easy fix is by ORDERing your query results and then add some logic in your foreach loop

$query->order('a.continent_name ASC, t.country_name ASC');

In your foreach loop remember what the previous continent was

<?php 
  $lastcontinent = "";
  foreach($menus as $k => $menu):
    if($lastcontinent != $menu->continent_name){
      if($k > 0){ // if this isn't the first continent
        // closing tags for the previous continent
        echo '</ul></div>';
      }
      echo '<div>'.$menu->continent_name.'</div><ul>';
    }      
    $lastcontinent = $menu->continent_name; 
    echo '<li id="'.$menu->country_code.'">'.$menu->country_name.'</li>';
  endforeach;
?>
</ul></div> <!-- closing tags for the last continent which hasn't been closed yet -->
Sign up to request clarification or add additional context in comments.

Comments

0

Use a foreach loop and make a new array and create continent_name as a key. Then you won't have a repetitive names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.