Function not generating valid nested lists

I’ve come up with a function to build a nested list from a flat array but I can’t figure out how to get it to produce valid nested lists. The function is…

        public function buildNestedList($items, $listid = 'category_list' )
        {

            $depth = 1;
            $output = "" ;
            foreach ($items as $item) {

                if ($item['depth'] > $depth) {
                    $depth++;
                    $output .= "<li><ul>";
                }

                while ($depth > $item['depth']) {
                    $depth--;
                    $output .= "</ul></li>";
                }

                $output .= "<li>{$item['name']}</li>";
            }

            while ($depth-- > 0) {
                $output .= "</ul></li>";
            }


         return $output;
         }

but it outputs…

<ul>
  <li>For Sale</li>
  <li>
    <ul>
      <li>Cars</li>
      <li>
        <ul>
          <li>Red</li>
          <li>Green</li>
          <li>Blue</li>
        </ul>
      </li>
      <li>Parts</li>
    </ul>
  </li>
  <li>Wanted</li>
  <li>
    <ul>
      <li>Cars</li>
      <li>Parts</li>
    </ul>
  </li>
</ul>

instead of…

<ul>
  <li>For Sale
    <ul>
      <li>Cars
        <ul>
          <li>Red</li>
          <li>Green</li>
          <li>Blue</li>
        </ul>
      </li>
      <li>Parts</li>
    </ul>
  </li>
  <li>Wanted
    <ul>
      <li>Cars</li>
      <li>Parts</li>
    </ul>
  </li>
</ul>

Does anybody have any idea how I can modify this to get the desired result. To me it seems the valid list format is actually the more illogical but what do I know? :slight_smile:

yeah the above thread have the answer for your question…this php things become a bit complicated if you dont understand deep…