Simple Array to Indented list Function

Converting a multidimensional array is not difficult given the function array_walk_recursive. However this does not work out if the keys of the sub-arrays have to be maintained.

Here is a simple example how I have done it.

Consider this is the input array:

$data = array('info' =>array('content_type' => 'text/html; charset=UTF-8',
                             'http_code' => 200,'header_size' => 321,
                            'request_size' => 94,'filetime' => -1
              'process_name' => 'create',
              'pid' => 20063,
              'curl_status' => 1,
              'response' => array('number_files_created' => 2,
              'total_file_size' => 2.4187936782837,
              'total_records' => 493,
              'time' => 1.3771939277649,
              'files' => array('0' => 'xyz_FULL_1.xml',
                               '1' => 'xyz_FULL_2.xml'

This is the function:

function arrayToUList($data) {
     //static because recursive
     static $ulCount = 0; //count of open <li>/<ul> tags
     static $output = ''; //collects output

     $iterator = new RecursiveArrayIterator($data);

     while($iterator->valid()) {
         // Check if there are children, i.e. any sub arrays?
         //if there are any sub arrays we need to recurse
        //till be reach only elements
        if($iterator->hasChildren()) {
            $iterator2 = $iterator->getChildren();
            //The key of the array now becmoes the sub title
            $output .= "<li>{$iterator->key()}: <ul>\n";

         } else {
              //just a plain element
              $output .= "<li>{$iterator->key()}: {$iterator->current()}</li>\n";
         //next element
      //no more elements left
      //let's close all unclosed <li>/<ul> tags
      while($ulCount > 0) {
          $output .= "</ul></li>\n";
      return $output;

In HTML code:

<ul id="example">
 echo arrayToUList($data);

The output can be seen here:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.