【问题标题】:PHP array loop to build ul li menuPHP数组循环构建ul li菜单
【发布时间】:2020-03-27 01:28:51
【问题描述】:

我有一个数组列表,我想将它列为菜单:

  • 如果item['parent']为空,则为父项。

  • 如果item['parent'] 等于item['id'],它将是此的子项

我要列出的数组:

$arr = array(
    [
        "name"   => "cat1",
        "id"     => "1",
        "parent" => "",
    ],
    [
        "name"   => "cat2",
        "id"     => "2",
        "parent" => "",
    ],
    [
        "name"   => "subcat1",
        "id"     => "6",
        "parent" => "1",
    ],
    [
        "name"   => "subcat2",
        "id"     => "6",
        "parent" => "2",
    ],
);

和我的 php 代码:

echo "<ul>";
foreach ($arr as $item) {
    if (!$item["parent"]) {
        $id = $item["id"];
        echo "<li>";
        echo $item["name"];
    }
    if ($item["parent"] == $id) {
        echo "<ul>";
        echo "<li>";
        echo $item["name"];
        echo "</li>";
        echo "</ul>";
    }
}
echo "</ul>";

【问题讨论】:

    标签: php arrays arraylist foreach


    【解决方案1】:

    假设您的嵌套只有一层,您可以使用此代码查找所有父级,然后遍历它们并将其所有子级显示为子列表。

    $parents = array_filter($arr, function ($item) { return !$item['parent'];});
    echo "<ul>\n";
    foreach ($parents as $parent) {
        echo "<li>{$parent['name']}</li>\n";
        // find the children
        $children = array_filter($arr, function ($item) use ($parent) { return $item['parent'] == $parent['id']; });
        if (!empty($children)) {
            echo "<ul>\n";
            foreach ($children as $child) {
                echo "<li>{$child['name']}</li>\n";
            }
            echo "</ul>\n";
        }
    }
    echo "</ul>\n";
    

    输出(用于您的样本数据):

    <ul>
    <li>cat1</li>
    <ul>
    <li>subcat1</li>
    </ul>
    <li>cat2</li>
    <ul>
    <li>subcat2</li>
    </ul>
    </ul>
    

    或作为 HTML:

    • cat1
      • subcat1
    • cat2
      • subcat2

    Demo on 3v4l.org

    如果你可以有比一层更深的嵌套,你需要将上面的代码重写为递归函数:

    function list_item($arr, $item) {
        echo "<li>{$item['name']}</li>\n";
        // find any children
        $children = array_filter($arr, function ($i) use ($item) { return $i['parent'] == $item['id']; });
        if (!empty($children)) {
            echo "<ul>\n";
            foreach ($children as $child) {
                list_item($arr, $child);
            }
            echo "</ul>\n";
        }
    }
    
    $parents = array_filter($arr, function ($item) { return !$item['parent'];});
    echo "<ul>\n";
    foreach ($parents as $parent) {
        list_item($arr, $parent);
    }
    echo "</ul>\n";
    

    Demo on 3v4l.org

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      相关资源
      最近更新 更多