【问题标题】:PHP array to ordered & nested HTML listPHP 数组到有序和嵌套的 HTML 列表
【发布时间】:2011-04-28 05:40:10
【问题描述】:

我在一个项目中使用 jQuery nestedSortable plugin。移动列表项时,我将数组序列化并将其保存到我的数据库中。我无法从 PHP 数组重新创建 HTML 列表。大概是因为晚了。 :)

我有以下 PHP 数组:

Array
(
    [list_4] => root
    [list_3] => 4
    [list_1303966373] => 3
    [list_1] => 1303966373
    [list_5] => 1
    [list_2] => 1
    [list_6] => root
)

它应该列出一个类似...的列表

<ol>
<li id='list_4'>value 4
  <ol>
    <li id='list_3'>value 3
      <ol>
        <li id='list_1303966373'>value 1303966373
          <ol>
            <li id='list_1'>value 1
              <ol>
                <li id='list_5'>value 5</li>
                <li id='list_2'>value 2</li>
              </ol>
            </li>
          </ol>
        </li>
      </ol>
    </li>
  </ol>
</li>
<li id='list_6'>value 6</li>          
</ol>

(忽略这些值,它们只是为了展示。)

HTML 列表可以有任意深度的嵌套列表。

我的大脑已经死了,我无法让它工作。有人有建议吗?我永远欠你饼干。还有一座城堡。

谢谢。 :)

【问题讨论】:

  • 这不是问题的关注点,但您可能想研究其他方法将此类列表保存到数据库中。
  • 请不要以数字开头 id,这会让婴儿哭泣w3.org/TR/html4/types.html(甚至在文档中也可以看到)
  • 大家好,这真的只是为了展示。实际列表的 id 前面带有“list_” 我将编辑前任以使婴儿感觉更好。 :)
  • @zneak 是的。解决此问题后,我打算将父 ID 与“值”表的每一行一起保存,以保存每个单独
  • 项目的信息。不过我还是会遇到这个问题,所以我想我会先过这座桥。
  • @Dylan - 你为什么不试试jquery treeview 这个...?
  • 标签: php jquery arrays list nested-sortable


    【解决方案1】:

    你有它(用你的样本测试OK):

    <?php
      $tree = array(
        "list_4" => "root",
        "list_3" => "list_4",
        "list_1303966373" => "list_3",
        "list_1" => "list_1303966373",
        "list_5" => "list_1",
        "list_2" => "list_1",
        "list_6" => "root",
     );
     function getChildrenLists($tree){
        $tree2 = array();
        foreach($tree as $child => $parent){
           if(!array_key_exists($parent, $tree2)) $tree2[$parent] = array();
           $tree2[$parent][] = $child;
        }
        return $tree2;
     }
    
     function renderTree($tree2, $parent = "root"){
        if($parent != "root") echo "<li id='$parent'> value $parent\n";
        $children = $tree2[$parent];
        if(count($children) > 0){ //If node has children
           echo "<ol>\n";
           foreach($children as $child)
              renderTree($tree2, $child);
           echo "</ol>\n";
        }
        if($parent != "root") echo "</li>\n";
     }
     $tree2 = getChildrenLists($tree); 
     renderTree($tree2);
    
    ?>
    

    我想要我的饼干!呵呵。希望对您有所帮助。

    【讨论】:

    • 我认为您可能只是炸弹.com。谢谢谢谢谢谢!
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签