doubi8512 2015-11-27 05:24 采纳率: 0%
浏览 28
已采纳

转换为嵌套格式的PHP

I just want some help in displaying the correct structure of the image data below. Basically what i want is to display it in nested form. From the data below, I would like it to display like this:

  • Engel (parent which parent_id = 0)
    • Chest Fridge - Freezers
      • Small Engel
      • digital platinum
    • Upright Fridge
      • Built-in fridge
    • Fridge Accessories
      • Blankets
      • Carry handles

enter image description here

I hope anyone can help me. Im using php fyi.

  • 写回答

1条回答 默认 最新

  • doufu9521 2015-11-27 06:15
    关注

    Do it recursively

    // For example, data fetched from database:
    $data = [
        ['id' => 1, 'sku' => 'name1', 'parent_id' => null],
        ['id' => 2, 'sku' => 'name12', 'parent_id' => 1],
        ['id' => 3, 'sku' => 'name12', 'parent_id' => 1],
        ['id' => 4, 'sku' => 'name2', 'parent_id' => null],
        ['id' => 5, 'sku' => 'name123', 'parent_id' => 2],
    ];
    
    // Recursive function
    function outTree($data, $parentId = null) {
        $str = '';
        foreach ($data as $row) {
            if ($row['parent_id'] == $parentId) {
                $str .= '<li>' . $row['sku'];
                $str .= outTree($data, $row['id']);
                $str .= '</li>';
            }
        }
        if ($str) {
            $str = '<ul>' . $str . '</ul>';
        }
        return $str;
    }
    
    echo outTree($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序