PHP:格式化多维数组作为HTML? [英] PHP: Formatting multi-dimensional array as HTML?
本文介绍了PHP:格式化多维数组作为HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让我的头围绕建设一个递归函数来处理未知的深度多维数组的格式为HTML和嵌套的div。我认为这应该是小菜一碟,但没有。
下面是我想出了这一步:
函数formatHtml($数组){
是$ var ='< DIV>'; 的foreach($数组作为$ K => $ V){ 如果(is_array($ V ['孩子'])及和放大器;!空($ V ['孩子'])){
formatHtml($ V ['孩子']);
}
其他{
。是$ var = $ V ['CID'];
}
} 是$ var ='< / DIV>'; 返回是$ var;
}
这是我的数组:
阵列
(
[1] =>排列
(
[CID] => 1
[_parent] =>
[ID] => 1
[名] => 根类
[儿童] =>排列
(
[2] =>排列
(
[CID] => 2
[_parent] => 1
[ID] => 3
[名] => 子类别
[儿童] =>阵列()
)
)
)
)
解决方案
您错过只有一个重要的一块:当您对递归调用 formatHtml()
你'其实重不包括任何地方返回的内容!其追加到 $ VAR
,你应该得到更好的结果:
函数formatHtml($数组){
是$ var ='< DIV>'; 的foreach($数组作为$ K => $ V){ 如果(is_array($ V ['孩子'])及和放大器;!空($ V ['孩子'])){
是$ var = formatHtml($ V ['孩子']);
}
其他{
。是$ var = $ V ['CID'];
}
} 是$ var ='< / DIV>'; 返回是$ var;
}
I have tried to get my head around building a recursive function to handle formatting of a unknown depth multi-dimensional array to HTML and nested Divs. I thought that it should be a piece of cake, but no.
Here's what I have come up with this far:
function formatHtml($array) {
$var = '<div>';
foreach ($array as $k => $v) {
if (is_array($v['children']) && !empty($v['children'])) {
formatHtml($v['children']);
}
else {
$var .= $v['cid'];
}
}
$var.= '</div>';
return $var;
}
And here's my array:
Array
(
[1] => Array
(
[cid] => 1
[_parent] =>
[id] => 1
[name] => 'Root category'
[children] => Array
(
[2] => Array
(
[cid] => 2
[_parent] => 1
[id] => 3
[name] => 'Child category'
[children] => Array ()
)
)
)
)
解决方案
You're missing only one important piece: when you make the recursive call to formatHtml()
you're not actually including the returned content anywhere! Append it to $var
and you should get much better results:
function formatHtml($array) {
$var = '<div>';
foreach ($array as $k => $v) {
if (is_array($v['children']) && !empty($v['children'])) {
$var .= formatHtml($v['children']);
}
else {
$var .= $v['cid'];
}
}
$var.= '</div>';
return $var;
}
这篇关于PHP:格式化多维数组作为HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文