up vote 0 down vote favorite

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!

link|flag

Please g-d, don't tell me that you're storing serialized data in a database. Please! – Jacob Relkin Sep 13 at 22:36
If there is a better way to store large arrays, then feel free to offer up the advice! :-) – LostInQuery Sep 13 at 22:41
1  
If you're just storing and regurtitating the data, then a serialized format is usually acceptable. If you need to work with the structure and store it efficiently, I recommend Set Trees: en.wikipedia.org/wiki/Nested_set_model – staticsan Sep 13 at 23:09

1 Answer

up vote 1 down vote accepted

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']);
link|flag
With a few tweaks to actually match my desired output, this script worked wonders! Thanks!! – LostInQuery Sep 14 at 17:32

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.