Skip to main content

Multi Dimensional Array as Nested List

12th October, 2022

Updated: 12th October, 2022

    First the array in 'php' syntax:

    <?php
    $a=array (
        '0' => array (
            'id' => 1,
            'title' => "Title 1",
            'parent_id' => 'NULL',
            'depth' => 0
        ),
        '1' => array (
            'id' => 2,
            'title' => "Title 2",
            'parent_id' => 'NULL',
            'depth' => 0
        ),
        '2' => array (
            'id' => 3,
            'title' => "Title 3",
            'parent_id' => 2,
            'depth' => 1
        ),
        '3' => array (
            'id' => 4,
            'title' => "Title 4",
            'parent_id' => 2,
            'depth' => 1
        ),
        '4' => array (
            'id' => 5,
            'title' => "Title 5",
            'parent_id' => 'NULL',
            'depth' => 0
        ),
        '5' => array (
            'id' => 6,
            'title' => "Title 6",
            'parent_id' => 4,
            'depth' => 0
        ));
    Here the code:
    
    $level = 'NULL';
    
    function r( $a, $level) {
      $r = "<ol>";
      foreach ( $a as $i ) {
          if ($i['parent_id'] == $level ) {
              $r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
          }
      }
      $r = $r . "</ol>";
      return $r;}
    
    print r( $a, $level );
    
    ?>

    The results:

    <ol><li>Title 1<ol></ol></li><li>Title 2<ol><li>Title 3<ol></ol></li><li>Title 4<ol><li>Title 6<ol></ol></li></ol></li></ol></li><li>Title 5
    <ol></ol></li></ol>
    • Title 1\n
    • Title 2\n
      • Title 3\n
      • Title 4\n
        • Title 6\n
    • Title 5\n

    To avoid empty leafs:

    function r( $a, $level) {
      $r = '' ;
      foreach ( $a as $i ) {
          if ($i['parent_id'] == $level ) {
              $r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
          }
      }
      return ($r==''?'':"<ol>". $r . "</ol>");}

    5882146f-45a7-4ad1-8f2a-91fbb0fce923

    Created on: 12th October, 2022

    Last updated: 12th October, 2022

    Source: php - Create nested list from Multidimensional Array - Stack Overflow

    Tagged With: