Create nested list from Multidimensional Array

后端 未结 3 1181
礼貌的吻别
礼貌的吻别 2020-12-03 08:31

I have an array in PHP, which looks like this:

array (
    [0] => array (
        [id] => 1
        [title] => \"Title 1\"
        [parent_id] =>         


        
3条回答
  •  失恋的感觉
    2020-12-03 09:19

    You should use recursion:

    First the array in 'php' syntax:

     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 = "
      "; foreach ( $a as $i ) { if ($i['parent_id'] == $level ) { $r = $r . "
    1. " . $i['title'] . r( $a, $i['id'] ) . "
    2. "; } } $r = $r . "
    "; return $r; } print r( $a, $level ); ?>

    The results:

    1. Title 1
      1. Title 2
        1. Title 3
        2. Title 4
          1. Title 6
        3. Title 5
          1. Title 1\n
            1. Title 2\n
              1. Title 3\n
                1. Title 4\n
                  1. Title 6\n
                2. Title 5\n

                  EDITED AFTER CHECK AS SOLUTION

                  To avoid empty leafs:

                  function r( $a, $level) {
                     $r = '' ;
                     foreach ( $a as $i ) {
                         if ($i['parent_id'] == $level ) {
                            $r = $r . "
                3. " . $i['title'] . r( $a, $i['id'] ) . "
                4. "; } } return ($r==''?'':"
                    ". $r . "
                  "); }

                提交回复
                热议问题