Skip to content Skip to sidebar Skip to footer

How To Create Two Dimensional Array To Multi-level Order List?

I have an php array is below, $two_dimention = array( array('id'=>4, 'name' => 'Home', 'parent' => 0, 'depth' => 0), array('id'=>5, 'name' => 'Menu 1', 'parent' =

Solution 1:

Here is the answer, created nested arrays from multi-dimensional array with ref

functionmakeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
    $m = [];
    foreach ($das$e) {
        isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];
        isset($m[$e[$k]]) ?: $m[$e[$k]]   = [];
        $m[$e[$pk]][]                     = array_merge($e, [$c => &$m[$e[$k]]]);
    }
    return$m[$r]; // remove [0] if there could be more than one root nodes
}
functionnested2ul($data)
{
    $result = [];
    if (sizeof($data) > 0) {
        $result[] = '<ul>';
        foreach ($dataas$entry) {
            $result[] = sprintf(
                '<li>%s %s</li>',
                $entry['name'],
                nested2ul($entry['children'])
            );
        }
        $result[] = '</ul>';
    }
    return implode($result);
}
$temp= makeRecursive($two_dimention);
echo nested2ul($temp);

Demo

Output

<ul><li>Home </li><li>Menu 1 </li><li>Menu 2
    <ul><li>Menu 2.1
        <ul><li>Menu 2.1.1 </li><li>Menu 2.1.2 </li></ul></li><li>Menu 2.2 </li></ul></li><li>Menu 3
    <ul><li>Menu 3.1 </li></ul></li></ul>

Post a Comment for "How To Create Two Dimensional Array To Multi-level Order List?"