将此数组转换为HTML列表

时间:2010-12-08 21:00:20

标签: php arrays

我有这个数组:

array
  0 => string '3,6' (length=3)
  3 => string '4,5' (length=3)
  4 => string '7,8' (length=3)
  8 => string '9' (length=1)

OR

array
  3 => 
    array
      4 => 
        array
          7 => null
          8 => 
            array
              9 => null
      5 => null
  6 => null

每个key都是ID,value是此父级子项的ID。
ID为0表示(3& 6)没有父级 现在,我想输出一个HTML列表,如:

  
      
  • 3   
        
    • 4   
          
      • 7
      •   
      • 8   
            
        • 9
        •   
      •   
    •   
    • 5
    •   
  •   
  • 6
  •   

2 个答案:

答案 0 :(得分:4)

$arr = array(
  0 => '3,6',
  3 => '4,5',
  4 => '7,8',
  8 => '9',
);
function writeList($items){
    global $arr;
    echo '<ul>';

    $items = explode(',', $items);
    foreach($items as $item){
        echo '<li>'.$item;
        if(isset($arr[$item]))
            writeList($arr[$item]);
        echo '</li>';
    }

    echo '</ul>';
}
writeList($arr[0]);

Test it.

$arr = array(
    3 => array(
        4 => array(
            7 => null,
            8 => array(
                9 => null
            ),
        ),
        5 => null,
    ),
    6 => null,
);
function writeList($items){
    if($items === null)
        return;
    echo '<ul>';
    foreach($items as $item => $children){
        echo '<li>'.$item;
        writeList($children);
        echo '</li>';
    }
    echo '</ul>';
}
writeList($arr);

答案 1 :(得分:1)

采用以下格式:

$data = array(
    3 => array(
        4 => array(
            7 => null,
            8 => array(
                9 => null
            )
        ),
        5 => null
    ),
    6 => null
);

这样做:

function writeList($tree)
{
    if($tree === null) return;
    echo "<ul>";
    foreach($tree as $node=>$children)
        echo "<li>", $node, writeList($children), '</li>';
    echo "</ul>";
}

writeList($data);

在此测试:http://codepad.org/MNoW94YU