jquery在数据库中可排序和序列化?

时间:2011-10-04 13:47:35

标签: php jquery arrays

我即将完成此操作,但我仍然坚持如何从数据库中获取值并使用正确的链接以正确的顺序显示<li></li>

到目前为止,我有这个:

HTML

    <ul id="navMenu">
    <li id="navMenu_1"><a href="http://www.example.com/home">Your Home</a></li>
    <li id="navMenu_2"><a href="#">Preferences</a></li>
    <li id="navMenu_3"><a href="#">Your Mailbox</a></li>
    <li id="navMenu_4"><a href="#">Game Updates</a></li>
    <li id="navMenu_5"><a href="#">Message Boards</a></li>
</ul>

JQUERY

$('#navMenu').sortable({

opacity: '0.8',
containment: '#navMenu',
cursor: 'move',
revert: true,
tolerance: 'pointer',
align: 'y',
update: function() {
    $.ajax({data: {navMenuLayout: $('#navMenu').sortable('serialize')}});
}
});

AJAX PHP

if (isset($_REQUEST['navMenuLayout'])) {

session_start();
$q = $dbc -> prepare("UPDATE layout SET navMenu = ? WHERE id = ?");
$q -> execute(array($_REQUEST['navMenuLayout'], $_SESSION['id']));
}

当用户更改列表的顺序时,一切正常,我将这样的字符串保存到我的数据库中。

navMenu[]=3&navMenu[]=1&navMenu[]=5&navMenu[]=2&navMenu[]=4

从数据库中有这个,我怎么能让php以正确的顺序回显上面的html,并为每个链接显示正确的文字?

1 个答案:

答案 0 :(得分:1)

假设您正在存储导航的顺序,您可以将它们放在一个数组中,然后遍历数组以正确的顺序显示菜单项

参见我在下面写的例子:

$nav_order = array("home" => '2',
                   "preferences" => '1',
                   "mailbox" => '4',
                   "game_updates" => '5',
                   "message_boards" => '3');

// Sort the menu items in to the right order
$sorted_order = sort($nav_order, SORT_NUMERIC);

// Start the list
echo '<ul id="navMenu">';

// Go through each item in the array, and show the menu item
foreach ($sorted_order AS $menu_key => $menu_order)
{
    switch($menu_key)
    {
        case "home":
              echo '<li id="navMenu_1"><a href="http://www.example.com/home">Your Home</a></li>';
              break;
        case "preferences":
              echo '<li id="navMenu_2"><a href="#">Preferences</a></li>';
              break;
        case "mailbox":
              echo '<li id="navMenu_3"><a href="#">Mailbox</a></li>';
              break;
        case "game_updates":
              echo '<li id="navMenu_4"><a href="#">Game updates</a></li>';
              break;
        case "message_boards":
              echo '<li id="navMenu_5"><a href="#">Message Boards</a></li>';
              break;
    }
}

// End the list
echo '</ul>';