我有以下数组的
$elemento =
["title"=> //Level 1
["iSh*t","text-center",40,"red"] //Level 2
];
$elemento2 =
["row"=>[ //Level 1
["col"=>[ //Level 2
["sm-6"=>[ //Level 3
["text"=> //Level 4
["Lorem ipsum sit amet","text-center",16,"blue"] //Level 5
]
]
],
["sm-6"=>[ //Level 3
["text"=> //Level 4
["Lorem ipsum sit amet","text-center",16,"blue"] //Level 5
]
]
],
["sm-6"=>[ //Level 3
["row"=>[ //Level 4
["col"=>[ //Level 5
["sm-6"=>[ //Level 6
["title" => //Level 7
["Lorem ipsum sit amet","text-center",16,"blue"] //Level 8
]
]
]
]
],
["col"=>[ //Level 5
["sm-6"=>[ //Level 6
["title" => //Level 7
["Lorem ipsum sit amet","text-center",16,"blue"] //Level 8
]
]
],
["sm-6"=>[ //Level 6
["title" => //Level 7
["Lorem ipsum sit amet","text-center",16,"blue"] //Level 8
]
]
]
]
]
]
]
]
]
]
]
]
];我希望创建一个函数,而不管我的数组中有多少个“级别”,都要在上迭代每个“级别”。
现在,我有一个函数,但是,是的,我知道它不是优化的,但我只想看看我如何使这个工作。
public function toHTML($superobj,$html){
$html = "<div class=\"bloque\"><div class=\"c-c\">";
XO::_html_get($superobj,$html);
$html = $html."</div></div>";
return $html;
}
private function _html_get($superobj,&$html){
foreach ($superobj as $i => $val) {
foreach ($val as $i => $val) {
switch ($i) {
case 'title':
$html = $html."<h1 class=\"".$val[1]."\" style=\"font-size:".$val[2]."px;color:".$val[3]."\">".$val[0]."</h1>";
break;
case 'text':
$html = $html."<p class=\"".$val[1]."\">".$val[0]."</p>";
break;
case 'image':
$html = $html."<img src=\"".$val[0]."\" class=\"".$val[1]."\">";
break;
case 'row':
$html = $html."<div class=\"row\">";
foreach ($val as $i => $val) {
foreach ($val as $i => $val) {
if ($i == "columna") {
foreach ($val as $i => $val) {
$html = $html."<div class=\"col-".array_keys($val)[0]."\">";
foreach ($val as $i => $val) {
foreach ($val as $i => $val) {
foreach ($val as $i => $val) {
if ($i == "texto") {
$html = $html."<p class=\"".$val[1]."\">".$val[0]."</p>";
}
}
}
}
$html = $html."</div>";
}
}
}
}
$html = $html."</div>";
break;
case 'row':
$html = $html."";
break;
case 'div':
$html = $html."";
break;
case 'button':
$html = $html."";
break;
case 'link':
$html = $html."";
break;
default:
# code...
break;
}
}
}
}现在,“工作”是,但如果我增加更多的级别3 (sm-6)将无法工作,因为函数没有准备好。
我知道不是优化和/或推荐的方式,但是. 我怎样才能做到?)
如果你想推荐我其他方法来做这个,请不要推荐我的框架,即使这使工作和任务变得容易,我不会学到任何东西,我喜欢“手动”代码。
发布于 2017-06-10 14:00:02
要达到的目的,一个非常简单的结构是:
function recursiveIteration ($array, &$html){
foreach ($array as $key => $value){
if (is_array($value)){
recursiveIteration($value, $html);
}
else {
$html .= intendedHtmlForThisItem($key);
}
}
}它允许创建任意多个级别。
https://stackoverflow.com/questions/44473983
复制相似问题