编程语言
首页 > 编程语言> > php – 从fetch Array创建无限的ul li标签(列表)

php – 从fetch Array创建无限的ul li标签(列表)

作者:互联网

我将创建一个无限列表使用我的数组PDO结果中的li和ul标签(取出)

我的阵列:

Array ( 
 [0] => Array ( [category_label] => catLevel4 [category_id] => 22 [category_owner] => 21 ) 
 [1] => Array ( [category_label] => catLevel3 [category_id] => 21 [category_owner] => 20 ) 
 [2] => Array ( [category_label] => catLevel2 [category_id] => 23 [category_owner] => 8 ) 
 [3] => Array ( [category_label] => catLevel2 [category_id] => 24 [category_owner] => 8 ) 
 [4] => Array ( [category_label] => catLevel2 [category_id] => 20 [category_owner] => 6 ) 
 [5] => Array ( [category_label] => catLevel1 [category_id] => 6 [category_owner] => 0 ) 
 [6] => Array ( [category_label] => catLevel1 [category_id] => 7 [category_owner] => 0 ) 
 [7] => Array ( [category_label] => catLevel1 [category_id] => 8 [category_owner] => 0 )
 )

我想要 :

catLevel1
 catLevel2
  catLevel3
   catLevel4
catLevel1
catLevel1
 catLevel2
 catLevel2

我做了转换功能:

function getCategory($parentCategoryId,$data)
{
    foreach($data as $row){if($row['category_owner']==$parentCategoryId){?>
    <li catId='<?php echo $row['category_id']?>'><a><?php echo $row['category_label'];?></a>
            <ul> 
            <?php getCategory($row['category_id'],$data) ;?>
            </ul>
    </li>
    <?php };}
}

echo getCategory(0,$this->categorysList);

这个函数非常适合我,但是创建null< ul>< / ul>对于所有项目!

感谢您帮助建立标准功能; D.

解决方法:

你得到null< ul>标签,因为您在没有任何检查的情况下对其进行硬编码,并在每次迭代中输出.尝试这样的事情:

<?php

function getCategory($parentCategoryId, $data) {
    foreach ($data as $row) {
        if ($row['category_owner'] == $parentCategoryId) {
            $str .= '
<li catId="' . $row['category_id'] . '"><a>' . $row['category_label'] . '</a>' . "\n";
            $res = getCategory($row['category_id'], $data);
            if ($res) {
                $str .= '
    <ul>' . $res . '</ul>
    ' . "\n";
            }
            $str .= '
</li>' . "\n";
        }
    }
    return $str;
}

$str = getCategory(0, $data);
echo $str;

?>

所以你得到这样的输出:

<li catId="6">
    <a> catLevel1</a>
    <ul>
        <li catId="20">
            <a> catLevel2</a>
            <ul>
                <li catId="21">
                    <a> catLevel3</a>
                    <ul>
                        <li catId="22">
                            <a> catLevel4</a>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</li>
<li catId="7">
    <a> catLevel1</a>
</li>
<li catId="8">
    <a> catLevel1</a>
    <ul>
        <li catId="23">
            <a> catLevel2</a>
        </li>
        <li catId="24">
            <a> catLevel2</a>
        </li>
    </ul>
</li>

标签:php,html-lists
来源: https://codeday.me/bug/20190704/1374254.html