猿问

如何创建二维数组到多级订单列表?

我有一个 php 数组在下面,


$two_dimention = array(

array("id"=>4, "name" => "Home", "parent" => 0, "depth" => 0),

array("id"=>5, "name" => "Menu 1", "parent" => 0, "depth" => 0),

array("id"=>6, "name" => "Menu 2", "parent" => 0, "depth" => 0),

array("id"=>8, "name" => "Menu 2.1", "parent" => 6, "depth" => 1),

array("id"=>10, "name" => "Menu 2.1.1", "parent" => 8,  "depth" => 2),

array("id"=>11, "name" => "Menu 2.1.2", "parent" => 8, "depth" => 2),

array("id"=>9, "name" => "Menu 2.2", "parent" => 6, "depth" => 1),

array("id"=>7, "name" => "Menu 3", "parent" => 0, "depth" => 0),

array("id"=>18, "name" => "Menu 3.1", "parent" => 7, "depth" => 1),

);

根据这个 $two_dimention 数组,它将创建 HTML 中的多维订单列表,如下所示,


 <ul>

    <li>Home</li>

    <li>Menu 1</li>

    <li>Menu 2

        <ul>

            <li>Menu 2.1

                <ul>

                    <li>Menu 2.1.1</li>

                    <li>Menu 2.1.2</li>

                </ul>

            </li>

            <li>Menu 2.2</li>

        </ul>

    </li>

    <li>Menu 3

        <ul>

            <li>Menu 3.1</li>

        </ul>

    </li>

</ul>

我怎样才能通过 PHP for/foreach 循环来做到这一点?


一只甜甜圈
浏览 127回答 1
1回答

慕森卡

这是答案,使用ref从多维数组创建嵌套数组function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children'){&nbsp; &nbsp; $m = [];&nbsp; &nbsp; foreach ($d as $e) {&nbsp; &nbsp; &nbsp; &nbsp; isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];&nbsp; &nbsp; &nbsp; &nbsp; isset($m[$e[$k]]) ?: $m[$e[$k]]&nbsp; &nbsp;= [];&nbsp; &nbsp; &nbsp; &nbsp; $m[$e[$pk]][]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= array_merge($e, [$c => &$m[$e[$k]]]);&nbsp; &nbsp; }&nbsp; &nbsp; return $m[$r]; // remove [0] if there could be more than one root nodes}function nested2ul($data){&nbsp; &nbsp; $result = [];&nbsp; &nbsp; if (sizeof($data) > 0) {&nbsp; &nbsp; &nbsp; &nbsp; $result[] = '<ul>';&nbsp; &nbsp; &nbsp; &nbsp; foreach ($data as $entry) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[] = sprintf(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '<li>%s %s</li>',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $entry['name'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nested2ul($entry['children'])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $result[] = '</ul>';&nbsp; &nbsp; }&nbsp; &nbsp; return implode($result);}$temp= makeRecursive($two_dimention);echo nested2ul($temp);输出<ul>&nbsp; <li>Home </li>&nbsp; <li>Menu 1 </li>&nbsp; <li>Menu 2&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li>Menu 2.1&nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>Menu 2.1.1 </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>Menu 2.1.2 </li>&nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; <li>Menu 2.2 </li>&nbsp; &nbsp; </ul>&nbsp; </li>&nbsp; <li>Menu 3&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li>Menu 3.1 </li>&nbsp; &nbsp; </ul>&nbsp; </li></ul>
随时随地看视频慕课网APP
我要回答