-1

Following function arranges the array totally wrong. Have you noticed any wrong piece of code in following function?

function buildHtmlList($array)
{
    $maxlevel = 0;

    foreach ($array as $key => $value)
    {
        $previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
        $nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;

        if ($value['parent'] != $previousparent)
        {
            echo "\n<ul>";
            ++$maxlevel;
        }

        echo "\n<li>" . $value['name'];

        if ($nextparent == $value['parent'])
            echo "</li>";
    }

    for ($i = 0; $i < $maxlevel; ++$i)
    {
        echo "\n</li>\n</ul>";
    }
}
heron
  • 3,611
  • 25
  • 80
  • 148
  • possible duplicate of [How can I convert a series of parent-child relationships into a hierarchical tree?](http://stackoverflow.com/questions/2915748/how-can-i-convert-a-series-of-parent-child-relationships-into-a-hierarchical-tre) – jeroen Nov 22 '11 at 16:09

2 Answers2

0

It arranges the array totally wrong. Have you noticed any wrong piece of code in following function?

The wrong piece is the whole logic of the function. You treat the array as a flat list (as it is!), however, you'd like to display a tree.

As a flat list can't be displayed as a tree, you need to change the flat list to a tree first and then write a function that displays a tree.

An example how to convert a flat array to a tree/multidimensional one is available in a previous answer.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • I have taken a look at http://codepad.viper-7.com/IUUDC4 can't figure out how it must look like in my case. My array's structure is different than example – heron Nov 22 '11 at 16:27
  • Add an example array to your question (why have you removed it?) then this should be possible to explain. – hakre Nov 23 '11 at 08:40
0

Try something like this (where $array is formatted like your example):

$corrected_array = array();
// This loop groups all of your entries by their parent
foreach( $array as $row)
{
    $corrected_array[ $row['parent'] ][] = $row['name'];
}

// This loop outputs the children of each parent
foreach( $corrected_array as $parent => $children)
{
    echo '<ul>';
    foreach( $children as $child)
    {
        echo '<li>' . $child . '</li>';
    }
    echo '</ul>';
}

Demo

nickb
  • 59,313
  • 13
  • 108
  • 143
  • where are the id's of li elements? where is the parent child structure? – heron Nov 22 '11 at 16:28
  • What IDs? Your example array has two items per elements, "parent" and "row". And the parent / child structure is pretty clear in the output of my demo... – nickb Nov 22 '11 at 23:52