Skip to content Skip to sidebar Skip to footer

Nested Array To Html List

I have the following array : Array ( [0] => Array ( [ID] => 1 [PARENT] => 0 [NAME] => Your first category )

Solution 1:

What I would do:

  1. group menu(?) items by their parent id - $menu[$parentID] = array($child, $child, ...)
  2. use recursive function for generating menu for each parent - makeMenu($menu, $parentID)

This will allow you to visit each node twice - first time, when reordering array, second time, when printing node. So it will work great with small as well as with large arrays.

Source:

$data = array(
    0 => array(
        'ID'     => '1',
        'PARENT' => '0',
        'NAME'   => 'Your first category',
    ),
    1 => array(
        'ID'     => '2',
        'PARENT' => '1',
        'NAME'   => 'Your first forum',
    ),
    2 => array(
        'ID'     => '4',
        'PARENT' => '1',
        'NAME'   => 'Another Forum',
    ),
    3 => array(
        'ID'     => '5',
        'PARENT' => '1',
        'NAME'   => 'Good Forum',
    ),
    4 => array(
        'ID'     => '6',
        'PARENT' => '0',
        'NAME'   => 'Top Forum',
    ),
    5 => array(
        'ID'     => '7',
        'PARENT' => '6',
        'NAME'   => 'Sub Forum #1',
    ),
    6 => array(
        'ID'     => '9',
        'PARENT' => '7',
        'NAME'   => 'Sub Forum #1-1',
    ),
    7 => array(
        'ID'     => '10',
        'PARENT' => '7',
        'NAME'   => 'Sub Forum #1-2',
    ),
    8 => array(
        'ID'     => '8',
        'PARENT' => '6',
        'NAME'   => 'Sub Forum #2',
    ),
);

// reorder array$menu = array();
foreach ( $dataas$item ) {
    $menu[$item['PARENT']][] = $item;
}

// print menufunctionmakeMenu($menu, $parentID) {
    $html = "<ul>";
    foreach ( $menu[$parentID] as$item ) {
        $html .= "<li id='{$item['ID']}'>{$item['NAME']}";
        if ( isset($menu[$item['ID']]) ) {
            $html .= makeMenu($menu, $item['ID']);
        }
        $html .= "</li>";
    }
    $html .= "</ul>";
    return$html;
}
echo makeMenu($menu, 0);

Output (added spacings manually):

<ul><liid='1'>
        Your first category
        <ul><liid='2'>Your first forum</li><liid='4'>Another Forum</li><liid='5'>Good Forum</li></ul></li><liid='6'>
        Top Forum
        <ul><liid='7'>Sub Forum #1
                <ul><liid='9'>Sub Forum #1-1</li><liid='10'>Sub Forum #1-2</li></ul></li><liid='8'>Sub Forum #2</li></ul></li></ul>

Solution 2:

$new_arr = array();
foreach($arras$data) $new_arr[$data['id']] = $data;

foreach($new_arras$id => &$data) $data['parent'] =& $new_arr[$data['parent']];

Now you have a proper array structure.

But you may have to turn it inside out, since it's structured by child. But your output is by parent.

So instead of the second foreach I posted, do this:

foreach($new_arras$id => $data) $new_arr[$data['parent']]['children'][] =& $data;

Post a Comment for "Nested Array To Html List"