Convert this array to HTML list

I have this array:

array
  0 => string '3,6' (length=3)
  3 => string '4,5' (length=3)
  4 => string '7,8' (length=3)
  8 => string '9' (length=1)

OR

array
  3 => 
    array
      4 => 
        array
          7 => null
          8 => 
            array
              9 => null
      5 => null
  6 => null

Each keyis id, and valueis id for the children of this parent.
The identifier 0 means that (3 and 6) do not have a parent.
Now I want to list the HTML, for example:

  • 3
    • 4
      • 7
      • 8
        • 9
    • 5
  • 6
0
source share
2 answers
$arr = array(
  0 => '3,6',
  3 => '4,5',
  4 => '7,8',
  8 => '9',
);
function writeList($items){
    global $arr;
    echo '<ul>';

    $items = explode(',', $items);
    foreach($items as $item){
        echo '<li>'.$item;
        if(isset($arr[$item]))
            writeList($arr[$item]);
        echo '</li>';
    }

    echo '</ul>';
}
writeList($arr[0]);

Check it out.

or

$arr = array(
    3 => array(
        4 => array(
            7 => null,
            8 => array(
                9 => null
            ),
        ),
        5 => null,
    ),
    6 => null,
);
function writeList($items){
    if($items === null)
        return;
    echo '<ul>';
    foreach($items as $item => $children){
        echo '<li>'.$item;
        writeList($children);
        echo '</li>';
    }
    echo '</ul>';
}
writeList($arr);
+4
source

Taking this format:

$data = array(
    3 => array(
        4 => array(
            7 => null,
            8 => array(
                9 => null
            )
        ),
        5 => null
    ),
    6 => null
);

Do it:

function writeList($tree)
{
    if($tree === null) return;
    echo "<ul>";
    foreach($tree as $node=>$children)
        echo "<li>", $node, writeList($children), '</li>';
    echo "</ul>";
}

writeList($data);

Test it here: http://codepad.org/MNoW94YU

+1
source

Source: https://habr.com/ru/post/1779293/


All Articles