2

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!

3
  • Please g-d, don't tell me that you're storing serialized data in a database. Please! Commented Sep 13, 2010 at 22:36
  • If there is a better way to store large arrays, then feel free to offer up the advice! :-) Commented Sep 13, 2010 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 Commented Sep 13, 2010 at 23:09

1 Answer 1

2

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']);
Sign up to request clarification or add additional context in comments.

1 Comment

With a few tweaks to actually match my desired output, this script worked wonders! Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.