如何创建二维数组到多级订单? [英] How to create two dimensional array to multi-level order list?
本文介绍了如何创建二维数组到多级订单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我下面有一个php数组,
I have an php array is below,
$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中创建多维订单列表,如下所示,
According to this $two_dimention array it will be created the multi-dimensional order list in HTML, that is look like below,
<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循环执行此操作?
How can I do this by PHP for/foreach loop?
推荐答案
这就是答案,使用参考
function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
$m = [];
foreach ($d as $e) {
isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];
isset($m[$e[$k]]) ?: $m[$e[$k]] = [];
$m[$e[$pk]][] = array_merge($e, [$c => &$m[$e[$k]]]);
}
return $m[$r]; // remove [0] if there could be more than one root nodes
}
function nested2ul($data)
{
$result = [];
if (sizeof($data) > 0) {
$result[] = '<ul>';
foreach ($data as $entry) {
$result[] = sprintf(
'<li>%s %s</li>',
$entry['name'],
nested2ul($entry['children'])
);
}
$result[] = '</ul>';
}
return implode($result);
}
$temp= makeRecursive($two_dimention);
echo nested2ul($temp);
输出
<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>
这篇关于如何创建二维数组到多级订单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文