views:

73

answers:

1

I am using the jQuery plugin from http://mjsarfatti.com/sandbox/nestedSortable/ It does an excellent job on easily sorting the list, but I am having issues with saving it a DB and loading it back up.

My question is once you get the array into PHP, serialize it and store it into a database, you end up with something along the lines of

a:1:{s:4:"page";a:4:{i:4;s:4:"root";i:2;s:1:"4";i:3;s:1:"2";i:1;s:1:"2";}}

Pulling it back out of the database, unserialize it and do a var_export I have

array ( 'page' => array ( 1 => 'root', 3 => 'root', 2 => '3', 4 => 'root', ), )

How do I then go through this array and make sure each child is correctly nested? The output should be in an unordered list like

page_1
page_3
 - page_2
Page_4

Or in real code

<ul>
  <li id="page_1">Page 1</li>
  <li id="page_3">Page 3
    <ul>
      <li id="page_2>Page 2</li>
    </ul>
  </li>
  <li id="page_4">Page 4</li>
</ul>

But once finished it will be huge and possibly 4-5 levels deep.

Thanks in advance!

+1  A: 

This should get you on your way:

function display_page_listings($arr, $parent = 'root')
{
    if($parent == 'root')
    {
        echo '<ul>';
    }
    $displayed = false;
    foreach($arr as $item_index => $item_parent)
    {
        if($item_parent == $parent)
        {
            if(!$displayed && $parent != 'root')
            {
                echo '<ul>';
                $displayed = true;
            }
            echo '<li id="page_' . $item_index . '">Page ' . $item_index;
            display_page_listings($arr, $item_index);
            echo '</li>';
        }
    }
    if($parent == 'root' || $displayed)
    {
        echo '</ul>';
    }
}

$arr = array(
    'page' => array ( 1 => 'root', 3 => 'root', 2 => '3', 4 => 'root')
);

display_page_listings($arr['page']);
Tim Cooper
With a few tweaks to actually match my desired output, this script worked wonders! Thanks!!
LostInQuery