簡體   English   中英

PHP 數組到有序和嵌套的 HTML 列表

[英]PHP array to ordered & nested HTML list

我在一個項目中使用 jQuery nestedSortable 插件 移動列表項時,我將數組序列化並將其保存到我的數據庫中。 我無法從 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 列表可以有任意深度的嵌套列表。

我的大腦已經死了,我無法讓它工作。 有人有建議嗎? 我永遠欠你 cookies。 還有一座城堡。

謝謝。 :)

在這里你有它(用你的樣本測試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);

?>

我要我的餅干。 呵呵。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM