5

I used the following stackoverflow thread, which was very helpful, in creating a sorted multilevel parent->child array.

The below is a sample multi-level (3 levels) parent->child sorted array based on the sorting method of the above stated thread:

Array 
( 
    [1] => Array 
        ( 
            [name] => User Manual 
            [parentId] => 0 
            [children] => Array
                ( 
                    [2] => Array 
                        ( 
                            [name] => Users 
                            [parentId] => 1 
                            [children] => Array 
                                ( 
                                    [4] => Array 
                                        ( 
                                            [name] => Privileges 
                                            [parentId] => 2 
                                        ) 
                                )
                        ) 
                    [3] => Array 
                        ( 
                            [name] => Reference 
                            [parentId] => 1 
                            [children] => Array 
                                ( 
                                    [5] => Array 
                                        ( 
                                            [name] =>  Glossary
                                            [parentId] => 3 
                                        ) 
                                    [6] => Array 
                                        ( 
                                            [name] =>  Index
                                            [parentId] => 3
                                        )
                                ) 
                        ) 
                )
        )
)

Now I'd like to take that sorted array and generate a single HTML SELECT that displays and represents the parent->child structure like the below example:

<option value='1'>User Manual</option>
<option value='2'>User Manual -> Users</option>
<option value='4'>User Manual -> Users -> Privileges</option>
<option value='3'>User Manual -> Reference</option>
<option value='5'>User Manual -> Reference -> Glossary</option>
<option value='6'>User Manual -> Reference -> Index</option>

The goal as seen above is to compile a display string that represents the multi-level parent/child path for each item. The VALUE to each option is the last item in the represented compiled string. So for the OPTION 'User Manual -> Users -> Privileges' the VALUE is the ID for Privileges, but the display text represents it's parent/child relationship in the array.

The select I create always ends up displaying the list of options like the below:

<option value='1'>User Manual</option>
<option value='2'>User Manual -> Users</option>
<option value='4'>Users -> Privileges</option>
<option value='3'>User Manual -> Reference</option>
<option value='5'>Reference -> Glossary</option>
<option value='6'>Reference -> Index</option>

You can see that it only is able to keep track of one level of the parent/child relationship.

My function that processes the array to create the selects options list is as follows:

function buildOptions($arr, $target, $parent = NULL) {
  $html = "";
  foreach ( $arr as $key => $v ) 
  {
    if (array_key_exists('children', $v))
    {
      if ( $key == $target )
        $html .= "<option value='$key' selected>$parent {$v['name']}</option>\n";
      else
        $html .= "<option value='$key'>$parent {$v['name']}</option>\n";

      $html .= buildOptions($v['children'],$target,$v['name']." > ");
    }
    else if ( $key == $target )
      $html .= "<option value='$key' selected>$parent {$v['name']}</option>\n";
    else
      $html .= "<option value='$key'>$parent {$v['name']}</option>\n";

  }

  return $html;
}

I'm having trouble in keeping track of the previous X parent.name when there is more than one level. Any help here would be welcomed. Thank you!

5
  • 2
    What does your array look like? Smells like recursion may be involved. Jul 25, 2011 at 5:48
  • Your right, I use recursion to get the 2 levels displayed so the problem I have is retaining the tree structure history past two levels. The problem is the recursion works through a pre-sorted array. It deals with each child and it's children as it progresses, naturally. So when it steps back to a prior child I'm having a hard time conceptualizing stepping back the string. Hopefully that makes sense. I'll update my post with an array example.
    – Brad
    Jul 25, 2011 at 6:13
  • @Brad: There is no recursive call in your snippet. What's toUL? What's $target? Would you consider using visual cues (indentation) instead of repeating the complete path for expressing hierarchy?
    – nikc.org
    Jul 25, 2011 at 6:46
  • @nikc: Sorry about that. I edited the post to fix that toUL. I renamed the function to buildOptions for this post and forgot to update the recursive callback. I would be interested in visual cues and would assume that the visual cues(indentation) would be based on the depth of the tree. I considered this but my mind hasn't been able to wrap itself around the idea as it seems very similar to what I'm originally trying to accomplish.
    – Brad
    Jul 25, 2011 at 6:57
  • @Brad: It is pretty much exactly the same, but with less bytes to transfer and less stuff to read for the end user ;-) [and you only need to pass an int down the recursion stack, replace $parent = null with $level = 0 and call buildOptions(<...>, $level + 1) and then use $level as a margin/padding multiplier.]
    – nikc.org
    Jul 25, 2011 at 7:39

1 Answer 1

3

Fix your recursive invocation this way, and you should get the full hierarchy on each node:

function buildOptions($arr, $target, $parent = NULL) {
  $html = "";
  foreach ( $arr as $key => $v )
  {
    if ( $key == $target )
      $html .= "<option value='$key' selected>$parent {$v['name']}</option>\n";
    else
      $html .= "<option value='$key'>$parent {$v['name']}</option>\n";

    if (array_key_exists('children', $v)) 
      $html .= buildOptions($v['children'],$target,$parent . $v['name']." > ");
  }

  return $html;
}
4
  • Thanks! I can't believe I was that close. Man..and I could swear I tried that. Too many hours staring at the same problem I think.
    – Brad
    Jul 25, 2011 at 7:07
  • I can't post my own answers yet as a follow up, but I slightly modified your response to check if (!$parent) then only print $v['name']." -> ", else print $parent.$v['name']." -> ".
    – Brad
    Jul 25, 2011 at 7:10
  • 1
    Just a note: If i stare too many hours at a problem I just stand up and go away...maybe to sniff some fresh air outside. 1-2 hour later I usually solve the problem within 10 minutes. This worked for me. :)
    – Adam Arold
    Jul 25, 2011 at 7:10
  • @edem: Indeed! guido: Your updated version worked flawless. Thanks again.
    – Brad
    Jul 25, 2011 at 7:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.