Skip to main content

Create nested list from Multidimensional Array

12th October, 2022

Updated: 12th October, 2022

    $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
        )
    );
    
    
    $level = 'NULL';
    
    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>");
    }
    
    print r( $a, $level );
    

    9694183f-fda4-4225-9082-b99e2130eeb0

    Created on: 12th October, 2022

    Last updated: 12th October, 2022

    Tagged With: