不知道我怎么能解释这个,但我们走了
我有一个数组如下:
$arr = array(
array('id' => 1,
'content' => '<h1>This is a simple Content</h1>',
'vars' => null,
'path' => 'holders/row.php',
'sub-page' => array(
'id' => 2,
'content' => '<h1>Sample Body Here</h1>',
'vars' => '{"title":"Sample Title Here"}',
'path' => 'holders/box.php',
'sub-page' => array(
'id' => 3,
'vars' => '{"title":"Sample Title NUmber 3 Here"}',
'content' => '<h1>Again Sample Body Here</h1>',
'path' => 'holders/box.php'
)
)
)
);
我在寻找的是
数组应该转到最深的sub-page
和json_decode
vars
键,并作为变量提取并包含文件。
完成此操作后,输出将传递到父级内容键并再次解析
这基本上是用于创建动态内容
holders/row.php
包含:
<div class="row">
<?= $content; ?>
</div>
和holders/box.php
包含:
<div class="box lite">
<div class="box-title">
<h4><?= $title; ?></h4>
<div class="tools">
<a href="javascript:;" class="collapse">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="box-body">
<?= $content; ?>
</div>
</div>
,所需的输出是:
<div class="row">
<div class="box lite">
<div class="box-title">
<h4>Sample Title Here</h4>
<div class="tools">
<a href="javascript:;" class="collapse">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="box-body">
<h1>Again Sample Body Here</h1>
<div class="box lite">
<div class="box-title">
<h4>Sample Title NUmber 3 Here</h4>
<div class="tools">
<a href="javascript:;" class="collapse">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="box-body">
<h1>Again Sample Body Here</h1>
</div>
</div>
</div>
</div>
</div>
我正在尝试循环数组,如下所示:
foreach ($arr as &$page) {
if (isset($page[$keyToParse])) {
$subMenu = $page[$keyToParse];
unset($page[$keyToParse]);
$page['content'] = $page['content'] . $this->parsePage($keyToParse, $subMenu);
return $page['content'];
} else {
$params = strlen($page['vars']) > 0 ? json_decode($page['vars'], true) : [];
$elementPath = $page['path'];
$params = array_merge($params, array('content' => $page['content']));
$page['content'] = callback(function () use ($params, $elementPath) {
extract($params);
include($elementPath);
});
return $page['content'];
}
,函数回调如下:
function callback($userfunc)
{
ob_start();
$userfunc();
$return = ob_get_contents();
ob_end_clean();
return $return;
}
请帮忙,因为我现在被困了很长时间
答案 0 :(得分:2)
所有你应该做的就是这样。
function renderNode($node){
ob_start();
if (isset($node["sub-page"]) && $node["sub-page"]){
$node["content"] = renderNode($node["sub-page"]);
}
extract($node);
include ($node["path"]);
return ob_get_clean();
}
然后调用它:
echo renderNode($arr[0]);