0

我有以下数组:

Array
(
    [0] => stdClass Object
        (
            [categoryid] => 60
            [categoryName] => Parent Category A
            [categoryParent] => 
        )

    [1] => stdClass Object
        (
            [categoryid] => 65
            [categoryName] => Parent Category B
            [categoryParent] => 
        )

    [2] => stdClass Object
        (
            [categoryid] => 68
            [categoryName] => Child Category A
            [categoryParent] => 65
        )

    [3] => stdClass Object
        (
            [categoryid] => 69
            [categoryName] => Super Child Category A
            [categoryParent] => 68
        )
)

我需要最终得到一个这样的列表:

  • 父类 A
  • 父类 B
    • 子类别 A
      • 超级儿童A类

最简单的方法是什么?

4

3 回答 3

2

试试这个:

function htmlList($array, $parent = null){
    $str = '<ul>';
    foreach($array as $object){
        if(!$parent){
            if(!$object->categoryParent){ 
                $str .= '<li>' . $object->categoryName;
                $str .= htmlList($array, $object->categoryid);
                $str .=  '</li>';
            }
        }
    }
    return $str .= '</ul>';
}

echo htmlList($yourArray);
于 2013-03-05T10:06:55.860 回答
1
function mylist( $a, $parent='') {
   $r = '' ;
   foreach ( $a as $i ) {
       if ($i['categoryParent'] == $parent ) {
          $r = $r . "<li>" . $i['categoryName'] . mylist( $a, $i['categoryid'] ) . "</li>";
       }
   }
   return ($r==''?'':"<ul>". $r . "</ul>");
}
于 2013-03-05T09:58:24.133 回答
0

我建议保留一个包含父项的数组,并将子项添加到自己的元素数组中。(类似于你的树)

您可以通过以下示例阅读此元素:

<?php
BuildList($arrayParent, 0);

function BuildList($arrayElements, $depth)
{
    foreach($arrayElements as $element)
    {
        echo str_repeat("&nbsp;&nbsp;", $depth) . $element->categoryName;
        $depth++;
        if(count($element->subCategory) > 0)
            $depth = BuildList($element->subCategory, $depth);

        return $depth;
    }
}
?>
于 2013-03-05T10:02:23.370 回答