将多维数组转换为List的最快方法?

时间:2013-03-05 09:52:07

标签: php

我有以下数组:

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

最简单的方法是什么?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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>");
}

答案 2 :(得分: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;
    }
}
?>