我有一个小应用程序,执行以下操作:如何在输出中包含子元素的每个子元素? PHP
- 允许用户在一个XML文件
- 解析XML文件上传到一个数组$ _SESSION
- 显示父列表工作元素名称,用户可以选择查看
- 解析阵列来显示所选父元素的孩子
的问题是,每项目可以有可以生孩子的孩子......等等,这可以无限期地继续下去。
如何在最终输出中包含孩子的每个孩子?
的XML文件可以类似于这样:
<thing>
<parents>
<parent>
<name>parent 1</name>
<categories>
<category>
<name>category 1</name>
<items>
<item>
<name>item 1 (gen 1)</name>
<items>
<item>
<name>sub-item 1 (gen 2)</name>
<items>
<item>
<name>sub-sub-item 1 (gen 3)</name>
...this could continue forever..
</item>
</items>
</item>
</items>
</item>
</items>
</category>
</categories>
</parent>
</parents>
</thing>
我在解析XML与PHP的SimpleXML的数组。每个文件都必须有父项,类别和第一代子项目。下面的代码解析了这三个层次的结构,但除此之外,我迷了路。
$output .= '<ul>';
foreach($xml['parents'] as $parent){
$output .= '<li>'.$parent['name'].'</li>';
foreach($parent['categories']['category'] as $category){
$output .= '<li>'.$category['name'].'</li>';
foreach($category['items']['item'] as $item){
$output .= '<li>'.$item['name'].'</li>';
// here is where the $item can have children w/ children
// who can have children who can have children... etc... forever.
// (i.e. $item['items']['item'] as $generation2_items++...)
//
// I want to add them as another <li></li>...
//
// How can you account for unknown # of children?
}
}
}
$output .= '</ul>';
echo $output;
码$输出类似于清单:
- parent 1
-- category 1
--- item 1 (gen 1)
---- sub item 1 (gen 2)
----- sub-sub item 1 (gen 3)
------- etc.
-------- etc.
你怎么能确定每个项目有多少子元素深云,然后你怎么能创造足够的回路通过相应的解析......或通过另一种方式迭代?
感谢您的帮助。
解决方案
PHP递归函数解决了这个问题。下面是我用,当我到了可能的无限重复的部分:
function foo($element, $indent=0){
$result .= '<li>';
if($indent > 0){
for($i=1;$i<=$indent;$i++){
$result .= ' ';
}
}
$result .= $element['name'].'</li>';
if(isset($element['children']['child'])){
$i++;
foreach($element['children']['child'] as $child){
$result .= foo($child, $i);
}
}
return $result;
}
$output .= foo($item);