How can I build a nested HTML list with an infinite depth from a flat array?

前端 未结 3 904
暗喜
暗喜 2021-01-06 10:00

I\'m trying to produce a multi-level HTML list from a source array that is formatted like this:

/**
 * id = unique id
 * parent_id = \"id\" that this item is         


        
3条回答
  •  孤街浪徒
    2021-01-06 10:30

    Tested and working :)

    $list = array(...);
    $nested = array();
    
    foreach ($list as $item)
    {
        if ($item['parent_id'] == 0)
        {
            // Woot, easy - top level
            $nested[$item['id']] = $item;
        }
        else
        {
            // Not top level, find it's place
            process($item, $nested);
        }
    }
    
    // Recursive function
    function process($item, &$arr)
    {
        if (is_array($arr))
        {
            foreach ($arr as $key => $parent_item)
            {
                // Match?
                if (isset($parent_item['id']) && $parent_item['id'] == $item['parent_id'])
                {
                    $arr[$key]['children'][$item['id']] = $item;
                }
                else
                {
                    // Keep looking, recursively
                    process($item, $arr[$key]);
                }
            }
        }
    }
    

提交回复
热议问题