[英]Recursively output a php array in nested div?
I have an array with a data structure like below 我有一个数组,其数据结构如下
$array = array(
'someKey' => array(
'id' => 1,
'string' => 'some key',
'someKey2' => array(
'id' => 1,
'string' => 'some key two',
'someKeyThree' => array(
'id' => 1,
'string' => 'some key three',
,
),
),
'someOtherKey' => array(
),
);
What I would like to do is out every array as a nested div p
structure, 我想做的是将每个数组都作为嵌套的
div p
结构,
<div>
<p>someKey</p> // key of first array value
<div>
<p>someKey2</p>
<div>
<p>SomeKeyThree</p>
</div>
</div>
</div>
I have tried using new RecursiveIteratorIterator(new RecursiveArrayIterator($this->getData(), RecursiveIteratorIterator::CHILD_FIRST));
我已经尝试使用
new RecursiveIteratorIterator(new RecursiveArrayIterator($this->getData(), RecursiveIteratorIterator::CHILD_FIRST));
and using that but I am having trouble as the end tag for div
never ends up right. 并使用它,但是我遇到了麻烦,因为
div
的结束标签永远不会结束。 Also once the iterator
reaches the bottom of an array with no array to go into I want it to stop iterating completely. 同样,一旦
iterator
到达数组的底部且没有数组可进入,我希望它完全停止迭代。
THanks 谢谢
You have to call a function recursively. 您必须递归调用函数。
function printUl($arr){
$output = "<ul>";
foreach ($arr as $key => $val){
if (is_array($val)){
$output .= printUl($val);
continue;
}
else{
$output .= "<li>".$val."</li>"
}
$output .= "</ul>";
return $output;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.