Revision [8993]

This is an old revision of ArrayToList made by JavaWoman on 2005-06-08 11:52:19.

 

Generating a List from an Array


See also:
This page presents new code for the WikkaCore Wikka Core to generate well-structured lists from an array of items to be presented.

Why?


In many cases we get an array back from some procedure and want to display the result in the form of a list. In several places in the Wikka code this now happens "manually" in that each uses its own code to build the HTML to present the list. This is not only inefficient, but also leads to inconsistent and sometimes not even well-structured code. (Example: the TextSearch produces a numbered list of matching page names - but it is not only not sorted, it is not even an ordered list.)

Using a standard way to generate lists is more efficient, can ensure consistent code and makes it easier to write methods (or actions or handlers) that need some kind of list as output.

How?


Two separate methods were written to make it easy to generate well-structured lists with 'hooks' for styling: the first does nothing but generate a list from an array (with an id); the second wraps that in a bit of code with a heading and a bit of text instead of the list if the array happens to be empty.

The Code


Constants

The methods make use of some constants (limits and texts used for error messages, ready for internationalization) that should be defined in the constants section in wikka.php.

Find the following line (line nr. as in version 1.1.6.0 release):
  1. define("WAKKA_VERSION", "1.1.6.0");


and insert the following block after it:
  1. /**#@+
  2.  * Numeric constant. May be made a configurable value.
  3.  */
  4. /**
  5.  * Length to use for generated part of id attribute.
  6.  */
  7. define('ID_LENGTH',10);                                         # @@@ maybe make length configurable
  8. /**
  9.  * Maximum indent level to use for generated lists.
  10.  */
  11. define('MAX_LIST_INDENT',20);                                   # @@@ maybe make max indent configurable)
  12. /**#@-*/
  13. /**#@+
  14.  * User-interface constant (ready for internationalization).
  15.  */
  16. define('STRUC_LIST','list');
  17. define('STRUC_COLS','columns');
  18. define('STRUC_ARRAY','array');
  19. /**
  20.  * Error message.
  21.  */
  22. define('ERR_CANNOTGEN','Cannot generate %1$s: %2$s required');
  23. /**#@-*/


(this should include a blank line as the start and at the end to separate it from the version number and the getmicrotime() function.

(The funny comment blocks are docblock "templates" to be used for documentation generation.)

makeList()

This method does the hard work of creating an unordered or ordered list. It requires the makeId() method to be already present - see GenerateUniqueId.

Add the following code in the //MISC section right after the makeId() method:

makeList()
  1.     /**
  2.      * Build a list from an array.
  3.      *
  4.      * Given an array, this method builds a simple unordered or ordered list
  5.      * with an id.
  6.      * Only a (simple) array is required which will generate an
  7.      * unordered list; optionally id, class, type of list and an indent level
  8.      * can be specified. For type 'menu' an unordered list is generated but
  9.      * with an id in group 'menu' instead of 'ul' or 'ol': this enables the
  10.      * list being styled as a menu.
  11.      *
  12.      * @author      {@link http://wikka.jsnx.com/JavaWoman JavaWoman}
  13.      * @copyright   Copyright © 2005, Marjolein Katsma
  14.      * @license     http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15.      * @version     0.8
  16.      *
  17.      * @todo    - support for nested lists (same type)
  18.      *          - support for definition lists
  19.      *
  20.      * @access  public
  21.      * @uses    makeId()
  22.      *
  23.      * @param   array   $array  required: flat array with content items
  24.      * @param   mixed   $id     optional: id for the list, will be treated with makeId()
  25.      *                          or FALSE which suppresses id (for multiple-use elements)
  26.      * @param   string  $class  optional: class for (extra) styling
  27.      * @param   string  $type   optional: type of list to generate; default: ul
  28.      * @param   integer $indent optional: indent level
  29.      * @return  string  generated list
  30.      */
  31.     function makeList($array,$id='',$class='',$type='ul',$indent=0)
  32.     {
  33.         static $validate = TRUE;                                    # need to validate input
  34.         // definition
  35.         $aTypes = array('ul','ol','menu');                          # (menu generates ul) @@@ add dl later
  36.         // validate/treat input
  37.         if ($validate)
  38.         {
  39.             if (!is_array($array))
  40.             {
  41.                 return '<p class="error">'.sprintf(ERR_CANNOTGEN,STRUC_LIST,STRUC_ARRAY).'</p>'."\n";
  42.             }
  43.             $type = (!in_array($type,$aTypes)) ? 'ul' : $type;
  44.             $class = trim(strip_tags($class));                      # minimum protection for user-supplied input
  45.             $indent = min(MAX_LIST_INDENT,abs((int)$indent));       # positive integer no larger than MAX_LIST_INDENT
  46.             $validate = FALSE;                                      # validation done: no need to repeat for recursion
  47.         }
  48.         // build element
  49.         $tag = ('menu' == $type) ? 'ul' : $type;
  50.         $ind = str_repeat("\t",$indent);
  51.         $attrId = (FALSE !== $id) ? ' id="'.$id = $this->makeId($type,$id).'"' : '';
  52.         $attrClass = ('' != $class) ? ' class="'.$class.'"' : '';
  53.         $out = $ind.'<'.$tag.$attrClass.$attrId.">\n";
  54.         foreach ($array as $item)
  55.         {
  56.             $out .= $ind.'  <li>';
  57.             if (!is_array($item))
  58.             {
  59.                 $out .= $item;
  60.             }
  61.             else
  62.             {
  63.                 # @@@ add recursion for nested lists
  64.                 $out .= 'nested list not yet supported';            # @@@ temporary string until recursion is implemented
  65.             }
  66.             $out .= "</li>\n";
  67.         }
  68.         $out .= $ind.'</'.$tag.">\n";
  69.         // return result
  70.         return $out;
  71.     }


makeMemberList()

This method is a wrapper around the makeList() method: it wraps the output in a div and adds a heading or outputs a paragraph of text in case the array turns out to be empty. It's meant for cases where items are to be presented as "members" of a collection; the heading is used to indicate the number of members.

There is deliberately no 'outer' div with an id: this is so a wrapper div may be created with a single heading containing several occurrences of the output of this method. Such a wrapper should be generated in the calling code.

Add the following code in the //MISC section right after the makeList() method:

makeMemberList()
  1.     /**
  2.      * Display members of a collection in a list. Wrapped in a div with a heading;
  3.      * alternatively output is just a paragraph of text in case the
  4.      * array provided turns out to be empty.
  5.      *
  6.      * There is deliberately no 'outer' div with an id: this is so a div may be
  7.      * created with a single heading containing several occurrences of the
  8.      * output of this method. Such a wrapper should be generated in the calling code.
  9.      *
  10.      * @todo    - allow suppression of the heading
  11.      *
  12.      * @author      {@link http://wikka.jsnx.com/JavaWoman JavaWoman}
  13.      * @copyright   Copyright © 2005, Marjolein Katsma
  14.      * @license     http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15.      * @version     0.6
  16.      *
  17.      * @access  public
  18.      * @uses    makeId()
  19.      * @uses    makeList()
  20.      *
  21.      * @param   array   $array      required: flat array with collection items
  22.      * @param   string  $hd         required: heading for the list;
  23.      *                              should contain a %d placeholder for the number of items
  24.      * @param   string  $hdid       required: id for the heading (should be a constant,
  25.      *                              because the heading itself has variable content)
  26.      * @param   string  $id         required: id for the list itself
  27.      * @param   string  $txtnone    required: text to display when the array is empty
  28.      * @param   string  $type       optional: type of list to generate; default: ul
  29.      * @param   integer $level      optional: level of the heading to generate; default: 6
  30.      * @return  string  div containing heading and list, or paragraph
  31.      */
  32.     function makeMemberList($array,$hd,$hdid,$id,$txtnone,$type='ul',$level=6)
  33.     {
  34.         // validate/sanitize input
  35.         if (!is_array($array))
  36.         {
  37.             return '<p class="error">'.sprintf(ERR_CANNOTGEN,STRUC_LIST,STRUC_ARRAY).'</p>'."\n";
  38.         }
  39.         $level = max(min((int)$level,6),3);                 # make sure level is in range 3-6
  40.         // initializations
  41.         $count = count($array);
  42.         $out = '';
  43.         // build structure
  44.         if ($count > 0)
  45.         {
  46.             $out .= "   <div>\n";
  47.             $out .= '       <h'.$level.' id="'.$this->makeId('hn',$hdid).'">'.sprintf($hd,$count).'</h'.$level.'>'."\n";
  48.             $out .= $this->makeList($array,$id,'',$type,2);
  49.             $out .= "   </div>\n";
  50.         }
  51.         else
  52.         {
  53.             $out .= '   <p>'.$txtnone.'</p>'."\n";
  54.         }
  55.         // return result
  56.         return $out;
  57.     }



When and where to use


In general, you can use these methods anywhere you get (or build) an array and want to display the result as a list - for instance for use in a sidebar as a navigation menu. (When the list is generated with id group 'menu' this can be used as a hook for a special 'menu' style in the stylesheet.)

Several current actions and handlers could take advantage of these methods, for example:

Updates for these (and possibly others) taking advantage of these new methods will soon be published on this site!

Status


As can be seen from the @version numbers and @todo items in the docblocks, the code is far from "finished".

Still, code as published here will change as it's being refined - so keep an eye on the page!


CategoryDevelopmentCore
There are no comments on this page.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki