我有一个小函数,它根据我的$ schema数组结构创建html输出。
我的新阵列结构可以使用相同的输出吗? (是否可以在函数内传递数组的索引名称)
我的原始数组结构。
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
)
);
我希望与函数
具有相同输出的新数组结构$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
'layer' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
)
)
);
我的功能
$vals = array('Country Name' => 'Usa', 'Country Name' => 'Canada');
function get_output($schema, $vals, $t = -2){
$t++; $tag = ""; $atts = array(); $keys = array(); $code = array();
foreach($schema as $k => $v){
if(is_array($v)){
$keys[] = get_output($v, $vals, $t);
} else {
switch($k){
case "tag": $tag = $v; break;
case "key": $keys[] = $v; break;
case "type": break;
default: $atts[$k] = $v; break;
}
}
}
if(0 < $t){ $code[] = "\n".str_repeat("\t", $t); }
if($tag){
$code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = ' '.$k.'="'.$v.'"'; } $code[] = ">";
$code = array(implode('', $code));
}
foreach($keys as $k){ $code[] = $k; }
if($tag){
$code[] = "\n".str_repeat("\t", $t);
$code[] = '</'.$tag.'>';
}
//print_r($code);
return implode("", $code);
}
echo get_output($schema, $vals);
感谢。